diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 94046873..9051fdd2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,10 +10,9 @@ on: jobs: lint: + timeout-minutes: 10 name: lint runs-on: ubuntu-latest - - steps: - uses: actions/checkout@v4 @@ -32,9 +31,9 @@ jobs: - name: Run lints run: ./scripts/lint test: + timeout-minutes: 10 name: test runs-on: ubuntu-latest - steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/publish-sonatype.yml b/.github/workflows/publish-sonatype.yml index a1f76188..bab4aea6 100755 --- a/.github/workflows/publish-sonatype.yml +++ b/.github/workflows/publish-sonatype.yml @@ -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.BRAINTRUST_SONATYPE_USERNAME || secrets.SONATYPE_USERNAME }} SONATYPE_PASSWORD: ${{ secrets.BRAINTRUST_SONATYPE_PASSWORD || secrets.SONATYPE_PASSWORD }} diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 6538ca91..6d78745c 100755 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.8.0" + ".": "0.9.0" } \ No newline at end of file diff --git a/.stats.yml b/.stats.yml index 24a7d1d7..91f6c416 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,4 @@ configured_endpoints: 110 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/manugoyal%2Fbraintrust-sdk-f0d64ce0e0efde75f9c171f7f3c3d4a72f00a77abb3bc5a7d65b7be1e715689b.yml +openapi_spec_hash: a027e48cc6aea2fab3cbdd38f4081119 +config_hash: 1ea10787f4def6c54a53f0e6f776f0a5 diff --git a/CHANGELOG.md b/CHANGELOG.md index 5898a8aa..9d47d1d9 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,88 @@ # Changelog +## 0.9.0 (2025-04-23) + +Full Changelog: [v0.8.0...v0.9.0](https://github.com/braintrustdata/braintrust-java/compare/v0.8.0...v0.9.0) + +### ⚠ BREAKING CHANGES + +* **client:** refactor exception structure and methods ([#164](https://github.com/braintrustdata/braintrust-java/issues/164)) +* **client:** **Migration:** Previously you would access error JSON on an exception via `exception.error()._additionalProperties()`, which would return `Map`. Now you would access this via `exception.body()`, which returns `JsonValue`. You should no longer assume that the returned error JSON is an object. You can check via `exception.body().asObject()`. + +### Features + +* **client:** add enum validation method ([7fe60b3](https://github.com/braintrustdata/braintrust-java/commit/7fe60b33c4097370f473c30564fccb8ce55e062a)) +* **client:** expose request body setter and getter ([#178](https://github.com/braintrustdata/braintrust-java/issues/178)) ([a36c0b6](https://github.com/braintrustdata/braintrust-java/commit/a36c0b633511abc41164b82429da85bd0810f732)) +* **client:** make datetime deserialization more lenient ([#177](https://github.com/braintrustdata/braintrust-java/issues/177)) ([a65987d](https://github.com/braintrustdata/braintrust-java/commit/a65987da85db749c526a110d7e624f38becf8fff)) +* **client:** make pagination robust to missing data ([445e30e](https://github.com/braintrustdata/braintrust-java/commit/445e30ebac1dd50e5cfc22aaf1ef9927fc13796f)) +* **client:** make union deserialization more robust ([#176](https://github.com/braintrustdata/braintrust-java/issues/176)) ([7fe60b3](https://github.com/braintrustdata/braintrust-java/commit/7fe60b33c4097370f473c30564fccb8ce55e062a)) +* **client:** support a lower jackson version ([#170](https://github.com/braintrustdata/braintrust-java/issues/170)) ([803e291](https://github.com/braintrustdata/braintrust-java/commit/803e2917444885e37e3148499f875ef59824f3c2)) +* **client:** support setting base URL via env var ([85b334a](https://github.com/braintrustdata/braintrust-java/commit/85b334ae4ce795835275970643f930468753d57a)) +* **client:** throw on incompatible jackson version ([803e291](https://github.com/braintrustdata/braintrust-java/commit/803e2917444885e37e3148499f875ef59824f3c2)) + + +### Bug Fixes + +* **client:** bump to better jackson version ([a2f69b5](https://github.com/braintrustdata/braintrust-java/commit/a2f69b5a6126c7c8ca17030bea1c0f660183f77f)) +* **client:** don't call `validate()` during deserialization if we don't have to ([#173](https://github.com/braintrustdata/braintrust-java/issues/173)) ([e71f053](https://github.com/braintrustdata/braintrust-java/commit/e71f0530ae5462de1089e41b3fefaaf18c140581)) +* **client:** limit json deserialization coercion ([#174](https://github.com/braintrustdata/braintrust-java/issues/174)) ([63e2b2c](https://github.com/braintrustdata/braintrust-java/commit/63e2b2ccb213bf215441d4c74dd4aa43f3697481)) +* **client:** map deserialization bug ([2a52b9f](https://github.com/braintrustdata/braintrust-java/commit/2a52b9fd35ea33391dad9f3e3098e5eb2afcca0d)) +* **client:** return `Optional<T>` instead of `Optional` ([#182](https://github.com/braintrustdata/braintrust-java/issues/182)) ([e3d5b19](https://github.com/braintrustdata/braintrust-java/commit/e3d5b190c14a9f398bfed2b8df461d01b411c1f3)) +* **client:** support kotlin 1.8 runtime ([#161](https://github.com/braintrustdata/braintrust-java/issues/161)) ([c9856ed](https://github.com/braintrustdata/braintrust-java/commit/c9856ed81fdfa4f17bdb96d66e45adc2751d4846)) +* pluralize `list` response variables ([#175](https://github.com/braintrustdata/braintrust-java/issues/175)) ([8d7b939](https://github.com/braintrustdata/braintrust-java/commit/8d7b939c590714e4344ea80d16b06414154cb691)) + + +### Performance Improvements + +* **client:** cached parsed type in `HttpResponseFor` ([#180](https://github.com/braintrustdata/braintrust-java/issues/180)) ([49c0c0a](https://github.com/braintrustdata/braintrust-java/commit/49c0c0af714e2770fe35456a046aff3a1d6759d8)) +* **internal:** improve compilation+test speed ([8efd75a](https://github.com/braintrustdata/braintrust-java/commit/8efd75a6d5b017099440e5dbb0b97d2b77d56c13)) + + +### Chores + +* **ci:** add timeout thresholds for CI jobs ([15222f8](https://github.com/braintrustdata/braintrust-java/commit/15222f8192f329d22b029a5839d56899d2fc8690)) +* **client:** refactor exception structure and methods ([#164](https://github.com/braintrustdata/braintrust-java/issues/164)) ([8463834](https://github.com/braintrustdata/braintrust-java/commit/8463834733a95f1afc905f3cfa74793b458e9a5a)) +* **client:** remove unnecessary json state from some query param classes ([7fe60b3](https://github.com/braintrustdata/braintrust-java/commit/7fe60b33c4097370f473c30564fccb8ce55e062a)) +* **internal:** add invalid json deserialization tests ([7fe60b3](https://github.com/braintrustdata/braintrust-java/commit/7fe60b33c4097370f473c30564fccb8ce55e062a)) +* **internal:** add json roundtripping tests ([7fe60b3](https://github.com/braintrustdata/braintrust-java/commit/7fe60b33c4097370f473c30564fccb8ce55e062a)) +* **internal:** codegen related update ([732dd76](https://github.com/braintrustdata/braintrust-java/commit/732dd768a9e4f048edf415d697e89c36551414d8)) +* **internal:** codegen related update ([#159](https://github.com/braintrustdata/braintrust-java/issues/159)) ([45cca50](https://github.com/braintrustdata/braintrust-java/commit/45cca506a7c0c1a165c0d4e54bf1950d4256d3a2)) +* **internal:** codegen related update ([#162](https://github.com/braintrustdata/braintrust-java/issues/162)) ([a490f5f](https://github.com/braintrustdata/braintrust-java/commit/a490f5fb5977d5347814c0d29a022468c8793e65)) +* **internal:** codegen related update ([#163](https://github.com/braintrustdata/braintrust-java/issues/163)) ([140986d](https://github.com/braintrustdata/braintrust-java/commit/140986d47b0e2f62d5ba3b84d459784e683fcda8)) +* **internal:** codegen related update ([#179](https://github.com/braintrustdata/braintrust-java/issues/179)) ([d32e7e5](https://github.com/braintrustdata/braintrust-java/commit/d32e7e5d3343041c4404178e0ebf48efd02ddc22)) +* **internal:** delete unused methods and annotations ([#171](https://github.com/braintrustdata/braintrust-java/issues/171)) ([2a52b9f](https://github.com/braintrustdata/braintrust-java/commit/2a52b9fd35ea33391dad9f3e3098e5eb2afcca0d)) +* **internal:** expand CI branch coverage ([6e596e4](https://github.com/braintrustdata/braintrust-java/commit/6e596e46185da32341ce8d186a96336f26b2cd56)) +* **internal:** fix example formatting ([#166](https://github.com/braintrustdata/braintrust-java/issues/166)) ([3ce1a02](https://github.com/braintrustdata/braintrust-java/commit/3ce1a023b3013ffeb9fa9651b42ef3ba5a11fc6e)) +* **internal:** generate more tests ([e7cdefc](https://github.com/braintrustdata/braintrust-java/commit/e7cdefcd06a55332f6e7ef6a6b729f33207a7834)) +* **internal:** make multipart assertions more robust ([6d40318](https://github.com/braintrustdata/braintrust-java/commit/6d403189bb05ab3934586907f2cb8f093e65c805)) +* **internal:** reduce CI branch coverage ([491a2ae](https://github.com/braintrustdata/braintrust-java/commit/491a2aeecc8b972efec17ec3e62e2848d1020158)) +* **internal:** reformat some tests ([#160](https://github.com/braintrustdata/braintrust-java/issues/160)) ([e7cdefc](https://github.com/braintrustdata/braintrust-java/commit/e7cdefcd06a55332f6e7ef6a6b729f33207a7834)) +* **internal:** remove unnecessary `assertNotNull` calls ([6d40318](https://github.com/braintrustdata/braintrust-java/commit/6d403189bb05ab3934586907f2cb8f093e65c805)) +* **internal:** remove unnecessary import ([#167](https://github.com/braintrustdata/braintrust-java/issues/167)) ([03d8ca9](https://github.com/braintrustdata/braintrust-java/commit/03d8ca931ab7599f98cef22d0b43a39b0d002f65)) +* **internal:** swap from `Builder().from(...)` to `toBuilder()` ([#172](https://github.com/braintrustdata/braintrust-java/issues/172)) ([d15ef50](https://github.com/braintrustdata/braintrust-java/commit/d15ef50ea2a826653c7b2ddebabefadc60b1864d)) +* **internal:** swap from `getNullable` to `getOptional` ([#181](https://github.com/braintrustdata/braintrust-java/issues/181)) ([2fca092](https://github.com/braintrustdata/braintrust-java/commit/2fca092faa8a4679ff792bfd746f9638a7187ba3)) +* **internal:** version bump ([#157](https://github.com/braintrustdata/braintrust-java/issues/157)) ([0492bdd](https://github.com/braintrustdata/braintrust-java/commit/0492bddf28ecfea9a5c901e78ff07918a265f6f6)) + + +### Documentation + +* add comments for page methods ([445e30e](https://github.com/braintrustdata/braintrust-java/commit/445e30ebac1dd50e5cfc22aaf1ef9927fc13796f)) +* add comments to `JsonField` classes ([e3d5b19](https://github.com/braintrustdata/braintrust-java/commit/e3d5b190c14a9f398bfed2b8df461d01b411c1f3)) +* **client:** update jackson compat error message ([6039ca5](https://github.com/braintrustdata/braintrust-java/commit/6039ca545cba51e71e02f4db3b26a0964f3bd522)) +* document how to forcibly omit required field ([e797de1](https://github.com/braintrustdata/braintrust-java/commit/e797de1a9185adb1dab8f9670fd2d8e4b03e2142)) +* explain http client customization ([1388be4](https://github.com/braintrustdata/braintrust-java/commit/1388be42ac426c5d1b934712302c6acecf20c885)) +* explain jackson compat in readme ([8fd288d](https://github.com/braintrustdata/braintrust-java/commit/8fd288d5ef4d5053f20b7db81bde980a465d996b)) +* minor readme tweak ([#169](https://github.com/braintrustdata/braintrust-java/issues/169)) ([4154acd](https://github.com/braintrustdata/braintrust-java/commit/4154acdf5be17f6b8c3ec26ccf5ca25b61c75404)) +* refine comments on multipart params ([#165](https://github.com/braintrustdata/braintrust-java/issues/165)) ([6d40318](https://github.com/braintrustdata/braintrust-java/commit/6d403189bb05ab3934586907f2cb8f093e65c805)) +* swap examples used in readme ([#183](https://github.com/braintrustdata/braintrust-java/issues/183)) ([e797de1](https://github.com/braintrustdata/braintrust-java/commit/e797de1a9185adb1dab8f9670fd2d8e4b03e2142)) +* update readme exception docs ([#168](https://github.com/braintrustdata/braintrust-java/issues/168)) ([39e01a6](https://github.com/braintrustdata/braintrust-java/commit/39e01a6fb2b29e1c8806ec27191cfef234b012d9)) + + +### Refactors + +* **client:** deduplicate page response classes ([445e30e](https://github.com/braintrustdata/braintrust-java/commit/445e30ebac1dd50e5cfc22aaf1ef9927fc13796f)) +* **client:** migrate pages to builder pattern ([b61888c](https://github.com/braintrustdata/braintrust-java/commit/b61888c0b3080b0ed42f8179a9fc772333cb0d9c)) + ## 0.8.0 (2025-03-18) Full Changelog: [v0.7.0...v0.8.0](https://github.com/braintrustdata/braintrust-java/compare/v0.7.0...v0.8.0) diff --git a/README.md b/README.md index 99c7eb77..18106805 100644 --- a/README.md +++ b/README.md @@ -2,18 +2,22 @@ -[![Maven Central](https://img.shields.io/maven-central/v/com.braintrustdata.api/braintrust-java)](https://central.sonatype.com/artifact/com.braintrustdata.api/braintrust-java/0.8.0) -[![javadoc](https://javadoc.io/badge2/com.braintrustdata.api/braintrust-java/0.8.0/javadoc.svg)](https://javadoc.io/doc/com.braintrustdata.api/braintrust-java/0.8.0) +[![Maven Central](https://img.shields.io/maven-central/v/com.braintrustdata.api/braintrust-java)](https://central.sonatype.com/artifact/com.braintrustdata.api/braintrust-java/0.9.0) +[![javadoc](https://javadoc.io/badge2/com.braintrustdata.api/braintrust-java/0.9.0/javadoc.svg)](https://javadoc.io/doc/com.braintrustdata.api/braintrust-java/0.9.0) -The Braintrust Java SDK provides convenient access to the Braintrust REST API from applications written in Java. +The Braintrust Java SDK provides convenient access to the [Braintrust REST API](https://www.braintrustdata.com/docs/api/spec) from applications written in Java. The Braintrust Java SDK is similar to the Braintrust Kotlin SDK but with minor differences that make it more ergonomic for use in Java, such as `Optional` instead of nullable values, `Stream` instead of `Sequence`, and `CompletableFuture` instead of suspend functions. It is generated with [Stainless](https://www.stainless.com/). -The REST API documentation can be found on [www.braintrustdata.com](https://www.braintrustdata.com/docs/api/spec). Javadocs are also available on [javadoc.io](https://javadoc.io/doc/com.braintrustdata.api/braintrust-java/0.7.0). + + +The REST API documentation can be found on [www.braintrustdata.com](https://www.braintrustdata.com/docs/api/spec). Javadocs are available on [javadoc.io](https://javadoc.io/doc/com.braintrustdata.api/braintrust-java/0.9.0). + + ## Installation @@ -22,16 +26,16 @@ The REST API documentation can be found on [www.braintrustdata.com](https://www. ### Gradle ```kotlin -implementation("com.braintrustdata.api:braintrust-java:0.8.0") +implementation("com.braintrustdata.api:braintrust-java:0.9.0") ``` ### Maven ```xml - com.braintrustdata.api - braintrust-java - 0.8.0 + com.braintrustdata.api + braintrust-java + 0.9.0 ``` @@ -49,7 +53,7 @@ import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient; import com.braintrustdata.api.models.Project; import com.braintrustdata.api.models.ProjectCreateParams; -// Configures using the `BRAINTRUST_API_KEY` environment variable +// Configures using the `BRAINTRUST_API_KEY` and `BRAINTRUST_BASE_URL` environment variables BraintrustClient client = BraintrustOkHttpClient.fromEnv(); ProjectCreateParams params = ProjectCreateParams.builder() @@ -66,7 +70,7 @@ Configure the client using environment variables: import com.braintrustdata.api.client.BraintrustClient; import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient; -// Configures using the `BRAINTRUST_API_KEY` environment variable +// Configures using the `BRAINTRUST_API_KEY` and `BRAINTRUST_BASE_URL` environment variables BraintrustClient client = BraintrustOkHttpClient.fromEnv(); ``` @@ -88,7 +92,7 @@ import com.braintrustdata.api.client.BraintrustClient; import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient; BraintrustClient client = BraintrustOkHttpClient.builder() - // Configures using the `BRAINTRUST_API_KEY` environment variable + // Configures using the `BRAINTRUST_API_KEY` and `BRAINTRUST_BASE_URL` environment variables .fromEnv() .apiKey("My API Key") .build(); @@ -96,9 +100,10 @@ BraintrustClient client = BraintrustOkHttpClient.builder() See this table for the available options: -| Setter | Environment variable | Required | Default value | -| -------- | -------------------- | -------- | ------------- | -| `apiKey` | `BRAINTRUST_API_KEY` | false | - | +| Setter | Environment variable | Required | Default value | +| --------- | --------------------- | -------- | ------------------------------ | +| `apiKey` | `BRAINTRUST_API_KEY` | false | - | +| `baseUrl` | `BRAINTRUST_BASE_URL` | true | `"https://api.braintrust.dev"` | > [!TIP] > Don't create more than one client in the same application. Each client has a connection pool and @@ -129,7 +134,7 @@ import com.braintrustdata.api.models.Project; import com.braintrustdata.api.models.ProjectCreateParams; import java.util.concurrent.CompletableFuture; -// Configures using the `BRAINTRUST_API_KEY` environment variable +// Configures using the `BRAINTRUST_API_KEY` and `BRAINTRUST_BASE_URL` environment variables BraintrustClient client = BraintrustOkHttpClient.fromEnv(); ProjectCreateParams params = ProjectCreateParams.builder() @@ -147,7 +152,7 @@ import com.braintrustdata.api.models.Project; import com.braintrustdata.api.models.ProjectCreateParams; import java.util.concurrent.CompletableFuture; -// Configures using the `BRAINTRUST_API_KEY` environment variable +// Configures using the `BRAINTRUST_API_KEY` and `BRAINTRUST_BASE_URL` environment variables BraintrustClientAsync client = BraintrustOkHttpClientAsync.fromEnv(); ProjectCreateParams params = ProjectCreateParams.builder() @@ -193,16 +198,16 @@ The SDK throws custom unchecked exception types: - [`BraintrustServiceException`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustServiceException.kt): Base class for HTTP errors. See this table for which exception subclass is thrown for each HTTP status code: - | Status | Exception | - | ------ | ------------------------------- | - | 400 | `BadRequestException` | - | 401 | `AuthenticationException` | - | 403 | `PermissionDeniedException` | - | 404 | `NotFoundException` | - | 422 | `UnprocessableEntityException` | - | 429 | `RateLimitException` | - | 5xx | `InternalServerException` | - | others | `UnexpectedStatusCodeException` | + | Status | Exception | + | ------ | -------------------------------------------------------------------------------------------------------------------------------------- | + | 400 | [`BadRequestException`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BadRequestException.kt) | + | 401 | [`UnauthorizedException`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/UnauthorizedException.kt) | + | 403 | [`PermissionDeniedException`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/PermissionDeniedException.kt) | + | 404 | [`NotFoundException`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/NotFoundException.kt) | + | 422 | [`UnprocessableEntityException`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/UnprocessableEntityException.kt) | + | 429 | [`RateLimitException`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/RateLimitException.kt) | + | 5xx | [`InternalServerException`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/InternalServerException.kt) | + | others | [`UnexpectedStatusCodeException`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/UnexpectedStatusCodeException.kt) | - [`BraintrustIoException`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustIoException.kt): I/O networking errors. @@ -278,6 +283,17 @@ Or to `debug` for more verbose logging: $ export BRAINTRUST_LOG=debug ``` +## 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 [`BraintrustOkHttpClient`](braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClient.kt) or [`BraintrustOkHttpClientAsync`](braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClientAsync.kt). + +> [!CAUTION] +> We make no guarantee that the SDK works correctly when the Jackson version check is disabled. + ## Network options ### Retries @@ -354,6 +370,42 @@ BraintrustClient client = BraintrustOkHttpClient.builder() .build(); ``` +### Custom HTTP client + +The SDK consists of three artifacts: + +- `braintrust-java-core` + - Contains core SDK logic + - Does not depend on [OkHttp](https://square.github.io/okhttp) + - Exposes [`BraintrustClient`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClient.kt), [`BraintrustClientAsync`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientAsync.kt), [`BraintrustClientImpl`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientImpl.kt), and [`BraintrustClientAsyncImpl`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientAsyncImpl.kt), all of which can work with any HTTP client +- `braintrust-java-client-okhttp` + - Depends on [OkHttp](https://square.github.io/okhttp) + - Exposes [`BraintrustOkHttpClient`](braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClient.kt) and [`BraintrustOkHttpClientAsync`](braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClientAsync.kt), which provide a way to construct [`BraintrustClientImpl`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientImpl.kt) and [`BraintrustClientAsyncImpl`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientAsyncImpl.kt), respectively, using OkHttp +- `braintrust-java` + - Depends on and exposes the APIs of both `braintrust-java-core` and `braintrust-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 [`braintrust-java` dependency](#installation) with `braintrust-java-core` +2. Copy `braintrust-java-client-okhttp`'s [`OkHttpClient`](braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/OkHttpClient.kt) class into your code and customize it +3. Construct [`BraintrustClientImpl`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientImpl.kt) or [`BraintrustClientAsyncImpl`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientAsyncImpl.kt), similarly to [`BraintrustOkHttpClient`](braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClient.kt) or [`BraintrustOkHttpClientAsync`](braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClientAsync.kt), using your customized client + +### Completely custom HTTP client + +To use a completely custom HTTP client: + +1. Replace your [`braintrust-java` dependency](#installation) with `braintrust-java-core` +2. Write a class that implements the [`HttpClient`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpClient.kt) interface +3. Construct [`BraintrustClientImpl`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientImpl.kt) or [`BraintrustClientAsyncImpl`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientAsyncImpl.kt), similarly to [`BraintrustOkHttpClient`](braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClient.kt) or [`BraintrustOkHttpClientAsync`](braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClientAsync.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. @@ -441,6 +493,19 @@ 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`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Values.kt): + +```java +import com.braintrustdata.api.core.JsonMissing; +import com.braintrustdata.api.models.ProjectCreateParams; + +ProjectCreateParams params = ProjectCreateParams.builder() + .name(JsonMissing.of()) + .build(); +``` + ### Response properties To access undocumented response properties, call the `_additionalProperties()` method: diff --git a/braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClient.kt b/braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClient.kt index 3800c0ed..aa4f40a4 100755 --- a/braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClient.kt +++ b/braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClient.kt @@ -29,13 +29,20 @@ class BraintrustOkHttpClient 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 proxy: Proxy? = null - fun baseUrl(baseUrl: String) = apply { - clientOptions.baseUrl(baseUrl) - this.baseUrl = baseUrl + fun baseUrl(baseUrl: String) = apply { clientOptions.baseUrl(baseUrl) } + + /** + * Whether to throw an exception if any of the Jackson versions detected at runtime are + * incompatible with the SDK's minimum supported Jackson version (2.13.4). + * + * Defaults to true. Use extreme caution when disabling this option. There is no guarantee + * that the SDK will work correctly when using an incompatible Jackson version. + */ + fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { + clientOptions.checkJacksonVersionCompatibility(checkJacksonVersionCompatibility) } fun jsonMapper(jsonMapper: JsonMapper) = apply { clientOptions.jsonMapper(jsonMapper) } @@ -161,7 +168,7 @@ class BraintrustOkHttpClient private constructor() { clientOptions .httpClient( OkHttpClient.builder() - .baseUrl(baseUrl) + .baseUrl(clientOptions.baseUrl()) .timeout(timeout) .proxy(proxy) .build() diff --git a/braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClientAsync.kt b/braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClientAsync.kt index 52efdd0a..c0d37976 100755 --- a/braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClientAsync.kt +++ b/braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/BraintrustOkHttpClientAsync.kt @@ -31,13 +31,20 @@ class BraintrustOkHttpClientAsync 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 proxy: Proxy? = null - fun baseUrl(baseUrl: String) = apply { - clientOptions.baseUrl(baseUrl) - this.baseUrl = baseUrl + fun baseUrl(baseUrl: String) = apply { clientOptions.baseUrl(baseUrl) } + + /** + * Whether to throw an exception if any of the Jackson versions detected at runtime are + * incompatible with the SDK's minimum supported Jackson version (2.13.4). + * + * Defaults to true. Use extreme caution when disabling this option. There is no guarantee + * that the SDK will work correctly when using an incompatible Jackson version. + */ + fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { + clientOptions.checkJacksonVersionCompatibility(checkJacksonVersionCompatibility) } fun jsonMapper(jsonMapper: JsonMapper) = apply { clientOptions.jsonMapper(jsonMapper) } @@ -163,7 +170,7 @@ class BraintrustOkHttpClientAsync private constructor() { clientOptions .httpClient( OkHttpClient.builder() - .baseUrl(baseUrl) + .baseUrl(clientOptions.baseUrl()) .timeout(timeout) .proxy(proxy) .build() diff --git a/braintrust-java-core/build.gradle.kts b/braintrust-java-core/build.gradle.kts index 4d9c5428..0e09ef31 100755 --- a/braintrust-java-core/build.gradle.kts +++ b/braintrust-java-core/build.gradle.kts @@ -3,15 +3,28 @@ plugins { id("braintrust.publish") } +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") + } +} + 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") @@ -21,6 +34,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/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/BaseDeserializer.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/BaseDeserializer.kt index 64d8a5b3..3ebb507f 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/BaseDeserializer.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/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/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Check.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Check.kt index 4a2305ea..7b05d4da 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Check.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Check.kt @@ -2,6 +2,9 @@ package com.braintrustdata.api.core +import com.fasterxml.jackson.core.Version +import com.fasterxml.jackson.core.util.VersionUtil + fun checkRequired(name: String, value: T?): T = checkNotNull(value) { "`$name` is required, but was not set" } @@ -39,3 +42,52 @@ internal fun checkMaxLength(name: String, value: String, maxLength: Int): String "`$name` must have at most length $maxLength, but was ${it.length}" } } + +@JvmSynthetic +internal fun checkJacksonVersionCompatibility() { + val incompatibleJacksonVersions = + RUNTIME_JACKSON_VERSIONS.mapNotNull { + val badVersionReason = BAD_JACKSON_VERSIONS[it.toString()] + when { + it.majorVersion != MINIMUM_JACKSON_VERSION.majorVersion -> + it to "incompatible major version" + it.minorVersion < MINIMUM_JACKSON_VERSION.minorVersion -> + it to "minor version too low" + it.minorVersion == MINIMUM_JACKSON_VERSION.minorVersion && + it.patchLevel < MINIMUM_JACKSON_VERSION.patchLevel -> + it to "patch version too low" + badVersionReason != null -> it to badVersionReason + else -> null + } + } + check(incompatibleJacksonVersions.isEmpty()) { + """ +This SDK requires a minimum Jackson version of $MINIMUM_JACKSON_VERSION, but the following incompatible Jackson versions were detected at runtime: + +${incompatibleJacksonVersions.asSequence().map { (version, incompatibilityReason) -> + "- `${version.toFullString().replace("/", ":")}` ($incompatibilityReason)" +}.joinToString("\n")} + +This can happen if you are either: +1. Directly depending on different Jackson versions +2. Depending on some library that depends on different Jackson versions, potentially transitively + +Double-check that you are depending on compatible Jackson versions. + +See https://www.github.com/braintrustdata/braintrust-java#jackson for more information. + """ + .trimIndent() + } +} + +private val MINIMUM_JACKSON_VERSION: Version = VersionUtil.parseVersion("2.13.4", null, null) +private val BAD_JACKSON_VERSIONS: Map = + mapOf("2.18.1" to "due to https://github.com/FasterXML/jackson-databind/issues/4639") +private val RUNTIME_JACKSON_VERSIONS: List = + listOf( + com.fasterxml.jackson.core.json.PackageVersion.VERSION, + com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION, + com.fasterxml.jackson.datatype.jdk8.PackageVersion.VERSION, + com.fasterxml.jackson.datatype.jsr310.PackageVersion.VERSION, + com.fasterxml.jackson.module.kotlin.PackageVersion.VERSION, + ) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/ClientOptions.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/ClientOptions.kt index 53b6d493..9841ea6e 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/ClientOptions.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/ClientOptions.kt @@ -16,6 +16,7 @@ class ClientOptions private constructor( private val originalHttpClient: HttpClient, @get:JvmName("httpClient") val httpClient: HttpClient, + @get:JvmName("checkJacksonVersionCompatibility") val checkJacksonVersionCompatibility: Boolean, @get:JvmName("jsonMapper") val jsonMapper: JsonMapper, @get:JvmName("clock") val clock: Clock, @get:JvmName("baseUrl") val baseUrl: String, @@ -27,6 +28,12 @@ private constructor( private val apiKey: String?, ) { + init { + if (checkJacksonVersionCompatibility) { + checkJacksonVersionCompatibility() + } + } + fun apiKey(): Optional = Optional.ofNullable(apiKey) fun toBuilder() = Builder().from(this) @@ -52,6 +59,7 @@ private constructor( class Builder internal constructor() { private var httpClient: HttpClient? = null + private var checkJacksonVersionCompatibility: Boolean = true private var jsonMapper: JsonMapper = jsonMapper() private var clock: Clock = Clock.systemUTC() private var baseUrl: String = PRODUCTION_URL @@ -65,6 +73,7 @@ private constructor( @JvmSynthetic internal fun from(clientOptions: ClientOptions) = apply { httpClient = clientOptions.originalHttpClient + checkJacksonVersionCompatibility = clientOptions.checkJacksonVersionCompatibility jsonMapper = clientOptions.jsonMapper clock = clientOptions.clock baseUrl = clientOptions.baseUrl @@ -78,6 +87,10 @@ private constructor( fun httpClient(httpClient: HttpClient) = apply { this.httpClient = httpClient } + fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { + this.checkJacksonVersionCompatibility = checkJacksonVersionCompatibility + } + fun jsonMapper(jsonMapper: JsonMapper) = apply { this.jsonMapper = jsonMapper } fun clock(clock: Clock) = apply { this.clock = clock } @@ -177,7 +190,12 @@ private constructor( fun removeAllQueryParams(keys: Set) = apply { queryParams.removeAll(keys) } - fun fromEnv() = apply { System.getenv("BRAINTRUST_API_KEY")?.let { apiKey(it) } } + fun baseUrl(): String = baseUrl + + fun fromEnv() = apply { + System.getenv("BRAINTRUST_BASE_URL")?.let { baseUrl(it) } + System.getenv("BRAINTRUST_API_KEY")?.let { apiKey(it) } + } /** * Returns an immutable instance of [ClientOptions]. @@ -220,6 +238,7 @@ private constructor( .maxRetries(maxRetries) .build() ), + checkJacksonVersionCompatibility, jsonMapper, clock, baseUrl, diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/ObjectMappers.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/ObjectMappers.kt index 588027c6..c3287a6b 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/ObjectMappers.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/ObjectMappers.kt @@ -2,38 +2,113 @@ package com.braintrustdata.api.core -import com.braintrustdata.api.errors.BraintrustException -import com.braintrustdata.api.errors.BraintrustInvalidDataException 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.Fail -import com.fasterxml.jackson.databind.cfg.CoercionInputShape.Integer -import com.fasterxml.jackson.databind.exc.InvalidDefinitionException -import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException +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.jacksonMapperBuilder +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.ZonedDateTime +import java.time.format.DateTimeFormatter +import java.time.temporal.ChronoField fun jsonMapper(): JsonMapper = - jacksonMapperBuilder() + JsonMapper.builder() + .addModule(kotlinModule()) .addModule(Jdk8Module()) .addModule(JavaTimeModule()) - .addModule(SimpleModule().addSerializer(InputStreamJsonSerializer)) + .addModule( + SimpleModule() + .addSerializer(InputStreamSerializer) + .addDeserializer(LocalDateTime::class.java, LenientLocalDateTimeDeserializer()) + ) + .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.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.Array) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Collection) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Map) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.POJO) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + } .serializationInclusion(JsonInclude.Include.NON_ABSENT) .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) .disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .disable(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS) - .withCoercionConfig(String::class.java) { it.setCoercion(Integer, Fail) } + .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) + .disable(MapperFeature.AUTO_DETECT_CREATORS) + .disable(MapperFeature.AUTO_DETECT_FIELDS) + .disable(MapperFeature.AUTO_DETECT_GETTERS) + .disable(MapperFeature.AUTO_DETECT_IS_GETTERS) + .disable(MapperFeature.AUTO_DETECT_SETTERS) .build() -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,37 +123,45 @@ private object InputStreamJsonSerializer : BaseSerializer(InputStre } } -@JvmSynthetic -internal fun enhanceJacksonException(fallbackMessage: String, e: Exception): Exception { - // These exceptions should only happen if our code is wrong OR if the user is using a binary - // incompatible version of `com.fasterxml.jackson.core:jackson-databind`: - // https://javadoc.io/static/com.fasterxml.jackson.core/jackson-databind/2.18.1/index.html - val isUnexpectedException = - e is UnrecognizedPropertyException || e is InvalidDefinitionException - if (!isUnexpectedException) { - return BraintrustInvalidDataException(fallbackMessage, e) - } +/** + * A deserializer that can deserialize [LocalDateTime] from datetimes, dates, and zoned datetimes. + */ +private class LenientLocalDateTimeDeserializer : + StdDeserializer(LocalDateTime::class.java) { - val jacksonVersion = JsonMapper::class.java.`package`.implementationVersion - if (jacksonVersion.isNullOrEmpty() || jacksonVersion == COMPILED_JACKSON_VERSION) { - return BraintrustInvalidDataException(fallbackMessage, e) + companion object { + + private val DATE_TIME_FORMATTERS = + listOf( + DateTimeFormatter.ISO_LOCAL_DATE_TIME, + DateTimeFormatter.ISO_LOCAL_DATE, + DateTimeFormatter.ISO_ZONED_DATE_TIME, + ) } - return BraintrustException( - """ - Jackson threw an unexpected exception and its runtime version ($jacksonVersion) mismatches the version the SDK was compiled with ($COMPILED_JACKSON_VERSION). + override fun logicalType(): LogicalType = LogicalType.DateTime - You may be using a version of `com.fasterxml.jackson.core:jackson-databind` that's not binary compatible with the SDK. + override fun deserialize(p: JsonParser, context: DeserializationContext?): LocalDateTime { + val exceptions = mutableListOf() - This can happen if you are either: - 1. Directly depending on a different Jackson version - 2. Depending on some library that depends on a different Jackson version, potentially transitively + for (formatter in DATE_TIME_FORMATTERS) { + try { + val temporal = formatter.parse(p.text) - Double-check that you are depending on a compatible Jackson version. - """ - .trimIndent(), - e, - ) -} + return when { + !temporal.isSupported(ChronoField.HOUR_OF_DAY) -> + LocalDate.from(temporal).atStartOfDay() + !temporal.isSupported(ChronoField.OFFSET_SECONDS) -> + LocalDateTime.from(temporal) + else -> ZonedDateTime.from(temporal).toLocalDateTime() + } + } catch (e: DateTimeException) { + exceptions.add(e) + } + } -const val COMPILED_JACKSON_VERSION = "2.18.1" + throw JsonParseException(p, "Cannot parse `LocalDateTime` from value: ${p.text}").apply { + exceptions.forEach { addSuppressed(it) } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Utils.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Utils.kt index 6761ce6a..6f9fb155 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Utils.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Utils.kt @@ -25,6 +25,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]. * diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Values.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Values.kt index c25a05d5..7f71390d 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Values.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Values.kt @@ -2,8 +2,6 @@ package com.braintrustdata.api.core import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JacksonAnnotationsInside -import com.fasterxml.jackson.annotation.JsonAutoDetect -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.core.JsonGenerator @@ -31,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) @@ -62,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) @@ -69,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) @@ -79,6 +110,12 @@ sealed class JsonField { fun asStringOrThrow(): String = asString().orElseThrow { BraintrustInvalidDataException("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) @@ -97,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) @@ -134,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 BraintrustInvalidDataException("`$name` is invalid, received $this") } @@ -149,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) { @@ -178,6 +239,7 @@ sealed class JsonField { * annotation. */ class IsMissing { + override fun equals(other: Any?): Boolean = other is JsonMissing override fun hashCode(): Int = Objects.hash() @@ -199,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() { @@ -206,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() @@ -217,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() @@ -232,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) { @@ -249,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) { @@ -270,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 @@ -294,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 @@ -350,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 @@ -371,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 @@ -393,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 @@ -417,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 @@ -441,51 +592,67 @@ 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 -@JacksonAnnotationsInside -@JsonAutoDetect( - getterVisibility = Visibility.NONE, - isGetterVisibility = Visibility.NONE, - setterVisibility = Visibility.NONE, - creatorVisibility = Visibility.NONE, - fieldVisibility = Visibility.NONE, -) -annotation class NoAutoDetect - +/** A class representing a field in a `multipart/form-data` request. */ class MultipartField private constructor( - @get:JvmName("value") val value: JsonField, + /** A [JsonField] value, which will be serialized to zero or more parts. */ + @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: JsonField, + /** A content type for the serialized parts. */ @get:JvmName("contentType") val contentType: String, private val filename: String?, ) { companion object { + /** + * Returns a [MultipartField] containing the given [value] as a [KnownValue]. + * + * [contentType] will be set to `application/octet-stream` if [value] is binary data, or + * `text/plain; charset=utf-8` otherwise. + */ @JvmStatic fun of(value: T?) = builder().value(value).build() + /** + * Returns a [MultipartField] containing the given [value]. + * + * [contentType] will be set to `application/octet-stream` if [value] is binary data, or + * `text/plain; charset=utf-8` otherwise. + */ @JvmStatic fun of(value: JsonField) = builder().value(value).build() + /** + * Returns a mutable builder for constructing an instance of [MultipartField]. + * + * The following fields are required: + * ```java + * .value() + * ``` + * + * If [contentType] is unset, then it will be set to `application/octet-stream` if [value] + * is binary data, or `text/plain; charset=utf-8` otherwise. + */ @JvmStatic fun builder() = Builder() } + /** Returns the filename directive that will be included in the serialized field. */ fun filename(): Optional = Optional.ofNullable(filename) @JvmSynthetic internal fun map(transform: (T) -> R): MultipartField = - MultipartField.builder() - .value(value.map(transform)) - .contentType(contentType) - .filename(filename) - .build() + builder().value(value.map(transform)).contentType(contentType).filename(filename).build() /** A builder for [MultipartField]. */ class Builder internal constructor() { @@ -502,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/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/handlers/ErrorHandler.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/handlers/ErrorHandler.kt index 12cfc384..f3b14814 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/handlers/ErrorHandler.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/handlers/ErrorHandler.kt @@ -1,12 +1,14 @@ +// File generated from our OpenAPI spec by Stainless. + @file:JvmName("ErrorHandler") package com.braintrustdata.api.core.handlers -import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.http.HttpResponse import com.braintrustdata.api.core.http.HttpResponse.Handler import com.braintrustdata.api.errors.BadRequestException -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.errors.InternalServerException import com.braintrustdata.api.errors.NotFoundException import com.braintrustdata.api.errors.PermissionDeniedException @@ -15,111 +17,68 @@ import com.braintrustdata.api.errors.UnauthorizedException import com.braintrustdata.api.errors.UnexpectedStatusCodeException import com.braintrustdata.api.errors.UnprocessableEntityException import com.fasterxml.jackson.databind.json.JsonMapper -import java.io.ByteArrayInputStream -import java.io.InputStream @JvmSynthetic -internal fun errorHandler(jsonMapper: JsonMapper): Handler { - val handler = jsonHandler(jsonMapper) +internal fun errorHandler(jsonMapper: JsonMapper): Handler { + val handler = jsonHandler(jsonMapper) - return object : Handler { - override fun handle(response: HttpResponse): BraintrustError = + return object : Handler { + override fun handle(response: HttpResponse): JsonValue = try { handler.handle(response) } catch (e: Exception) { - BraintrustError.builder().build() + JsonMissing.of() } } } @JvmSynthetic -internal fun Handler.withErrorHandler(errorHandler: Handler): Handler = +internal fun Handler.withErrorHandler(errorHandler: Handler): Handler = object : Handler { - override fun handle(response: HttpResponse): T { + override fun handle(response: HttpResponse): T = when (val statusCode = response.statusCode()) { - in 200..299 -> { - return this@withErrorHandler.handle(response) - } - 400 -> { - val buffered = response.buffered() - throw BadRequestException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - 401 -> { - val buffered = response.buffered() - throw UnauthorizedException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - 403 -> { - val buffered = response.buffered() - throw PermissionDeniedException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - 404 -> { - val buffered = response.buffered() - throw NotFoundException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - 422 -> { - val buffered = response.buffered() - throw UnprocessableEntityException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - 429 -> { - val buffered = response.buffered() - throw RateLimitException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - in 500..599 -> { - val buffered = response.buffered() - throw InternalServerException( - statusCode, - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - else -> { - val buffered = response.buffered() - throw UnexpectedStatusCodeException( - statusCode, - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } + in 200..299 -> this@withErrorHandler.handle(response) + 400 -> + throw BadRequestException.builder() + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() + 401 -> + throw UnauthorizedException.builder() + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() + 403 -> + throw PermissionDeniedException.builder() + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() + 404 -> + throw NotFoundException.builder() + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() + 422 -> + throw UnprocessableEntityException.builder() + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() + 429 -> + throw RateLimitException.builder() + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() + in 500..599 -> + throw InternalServerException.builder() + .statusCode(statusCode) + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() + else -> + throw UnexpectedStatusCodeException.builder() + .statusCode(statusCode) + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() } - } - } - -private fun HttpResponse.buffered(): HttpResponse { - val body = body().readBytes() - - return object : HttpResponse { - override fun statusCode(): Int = this@buffered.statusCode() - - override fun headers(): Headers = this@buffered.headers() - - override fun body(): InputStream = ByteArrayInputStream(body) - - override fun close() = this@buffered.close() } -} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/handlers/JsonHandler.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/handlers/JsonHandler.kt index ae855a7b..70259a46 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/handlers/JsonHandler.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/handlers/JsonHandler.kt @@ -2,9 +2,9 @@ package com.braintrustdata.api.core.handlers -import com.braintrustdata.api.core.enhanceJacksonException import com.braintrustdata.api.core.http.HttpResponse import com.braintrustdata.api.core.http.HttpResponse.Handler +import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.databind.json.JsonMapper import com.fasterxml.jackson.module.kotlin.jacksonTypeRef @@ -15,6 +15,6 @@ internal inline fun jsonHandler(jsonMapper: JsonMapper): Handler try { jsonMapper.readValue(response.body(), jacksonTypeRef()) } catch (e: Exception) { - throw enhanceJacksonException("Error reading response", e) + throw BraintrustInvalidDataException("Error reading response", e) } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpRequestBodies.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpRequestBodies.kt index bb5b61ab..2ab71012 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpRequestBodies.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpRequestBodies.kt @@ -9,7 +9,6 @@ import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.json.JsonMapper import com.fasterxml.jackson.databind.node.JsonNodeType -import java.io.ByteArrayInputStream import java.io.InputStream import java.io.OutputStream import kotlin.jvm.optionals.getOrNull @@ -74,12 +73,12 @@ internal fun multipartFormData( when (node.nodeType) { JsonNodeType.MISSING, JsonNodeType.NULL -> emptySequence() - JsonNodeType.BINARY -> sequenceOf(name to ByteArrayInputStream(node.binaryValue())) - JsonNodeType.STRING -> sequenceOf(name to node.textValue().toInputStream()) + JsonNodeType.BINARY -> sequenceOf(name to node.binaryValue().inputStream()) + JsonNodeType.STRING -> sequenceOf(name to node.textValue().inputStream()) JsonNodeType.BOOLEAN -> - sequenceOf(name to node.booleanValue().toString().toInputStream()) + sequenceOf(name to node.booleanValue().toString().inputStream()) JsonNodeType.NUMBER -> - sequenceOf(name to node.numberValue().toString().toInputStream()) + sequenceOf(name to node.numberValue().toString().inputStream()) JsonNodeType.ARRAY -> sequenceOf( name to @@ -104,7 +103,7 @@ internal fun multipartFormData( } } .joinToString(",") - .toInputStream() + .inputStream() ) JsonNodeType.OBJECT -> node.fields().asSequence().flatMap { (key, value) -> @@ -117,7 +116,7 @@ internal fun multipartFormData( ) } - private fun String.toInputStream(): InputStream = ByteArrayInputStream(toByteArray()) + private fun String.inputStream(): InputStream = toByteArray().inputStream() override fun writeTo(outputStream: OutputStream) = entity.writeTo(outputStream) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpResponse.kt index 901b030b..dbfbe2cb 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpResponse.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpResponse.kt @@ -1,7 +1,8 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.core.http import java.io.InputStream -import java.lang.AutoCloseable interface HttpResponse : AutoCloseable { diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpResponseFor.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpResponseFor.kt index 6cb31fa8..a8b0e532 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpResponseFor.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/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/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/RetryingHttpClient.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/RetryingHttpClient.kt index 56bdac87..830c55cc 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/RetryingHttpClient.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/RetryingHttpClient.kt @@ -23,6 +23,7 @@ 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?, @@ -62,10 +63,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) } } @@ -111,10 +112,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) } } @@ -179,7 +180,7 @@ private constructor( // retried. throwable is IOException || throwable is BraintrustIoException - 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 +227,40 @@ 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 = + object : Sleeper { + + private val timer = Timer("RetryingHttpClient", 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 + } + } private var clock: Clock = Clock.systemUTC() private var maxRetries: Int = 2 private var idempotencyHeader: String? = null fun httpClient(httpClient: HttpClient) = apply { this.httpClient = httpClient } + @JvmSynthetic internal 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,9 +270,17 @@ private constructor( fun build(): HttpClient = RetryingHttpClient( checkRequired("httpClient", httpClient), + sleeper, clock, maxRetries, idempotencyHeader, ) } + + internal interface Sleeper { + + fun sleep(duration: Duration) + + fun sleepAsync(duration: Duration): CompletableFuture + } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BadRequestException.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BadRequestException.kt index b8c65254..9e02c395 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BadRequestException.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BadRequestException.kt @@ -1,6 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class BadRequestException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + BraintrustServiceException("400: $body", cause) { + + override fun statusCode(): Int = 400 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [BadRequestException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [BadRequestException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(badRequestException: BadRequestException) = apply { + headers = badRequestException.headers + body = badRequestException.body + cause = badRequestException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class BadRequestException(headers: Headers, body: String, error: BraintrustError) : - BraintrustServiceException(400, headers, body, error) + /** + * Returns an immutable instance of [BadRequestException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): BadRequestException = + BadRequestException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustError.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustError.kt deleted file mode 100755 index 42865ed6..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustError.kt +++ /dev/null @@ -1,82 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.errors - -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import java.util.Objects - -@NoAutoDetect -class BraintrustError -@JsonCreator -private constructor( - @JsonAnyGetter - @ExcludeMissing - @JsonAnySetter - @get:JvmName("additionalProperties") - val additionalProperties: Map = immutableEmptyMap() -) { - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [BraintrustError]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [BraintrustError]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(braintrustError: BraintrustError) = apply { - additionalProperties = braintrustError.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 [BraintrustError]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): BraintrustError = BraintrustError(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is BraintrustError && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalProperties) /* spotless:on */ - - override fun toString() = "BraintrustError{additionalProperties=$additionalProperties}" -} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustServiceException.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustServiceException.kt index 728ac6bd..ebb6267b 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustServiceException.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustServiceException.kt @@ -1,23 +1,17 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.http.Headers abstract class BraintrustServiceException -@JvmOverloads -constructor( - private val statusCode: Int, - private val headers: Headers, - private val body: String, - private val error: BraintrustError, - message: String = "$statusCode: $error", - cause: Throwable? = null, -) : BraintrustException(message, cause) { - - fun statusCode(): Int = statusCode +protected constructor(message: String, cause: Throwable? = null) : + BraintrustException(message, cause) { - fun headers(): Headers = headers + abstract fun statusCode(): Int - fun body(): String = body + abstract fun headers(): Headers - fun error(): BraintrustError = error + abstract fun body(): JsonValue } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/InternalServerException.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/InternalServerException.kt index 36cc4432..9834c41a 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/InternalServerException.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/InternalServerException.kt @@ -1,10 +1,91 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class InternalServerException +private constructor( + private val statusCode: Int, + private val headers: Headers, + private val body: JsonValue, + cause: Throwable?, +) : BraintrustServiceException("$statusCode: $body", cause) { + + override fun statusCode(): Int = statusCode + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [InternalServerException]. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InternalServerException]. */ + class Builder internal constructor() { + + private var statusCode: Int? = null + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(internalServerException: InternalServerException) = apply { + statusCode = internalServerException.statusCode + headers = internalServerException.headers + body = internalServerException.body + cause = internalServerException.cause + } + + fun statusCode(statusCode: Int) = apply { this.statusCode = statusCode } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class InternalServerException( - statusCode: Int, - headers: Headers, - body: String, - error: BraintrustError, -) : BraintrustServiceException(statusCode, headers, body, error) + /** + * Returns an immutable instance of [InternalServerException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InternalServerException = + InternalServerException( + checkRequired("statusCode", statusCode), + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/NotFoundException.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/NotFoundException.kt index ecc1a307..d31d5688 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/NotFoundException.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/NotFoundException.kt @@ -1,6 +1,76 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class NotFoundException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + BraintrustServiceException("404: $body", cause) { + + override fun statusCode(): Int = 404 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [NotFoundException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [NotFoundException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(notFoundException: NotFoundException) = apply { + headers = notFoundException.headers + body = notFoundException.body + cause = notFoundException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class NotFoundException(headers: Headers, body: String, error: BraintrustError) : - BraintrustServiceException(404, headers, body, error) + /** + * Returns an immutable instance of [NotFoundException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): NotFoundException = + NotFoundException(checkRequired("headers", headers), checkRequired("body", body), cause) + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/PermissionDeniedException.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/PermissionDeniedException.kt index 27380e3e..b6926f3f 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/PermissionDeniedException.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/PermissionDeniedException.kt @@ -1,6 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class PermissionDeniedException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + BraintrustServiceException("403: $body", cause) { + + override fun statusCode(): Int = 403 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [PermissionDeniedException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PermissionDeniedException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(permissionDeniedException: PermissionDeniedException) = apply { + headers = permissionDeniedException.headers + body = permissionDeniedException.body + cause = permissionDeniedException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class PermissionDeniedException(headers: Headers, body: String, error: BraintrustError) : - BraintrustServiceException(403, headers, body, error) + /** + * Returns an immutable instance of [PermissionDeniedException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): PermissionDeniedException = + PermissionDeniedException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/RateLimitException.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/RateLimitException.kt index a9352a3a..cb32fed9 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/RateLimitException.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/RateLimitException.kt @@ -1,6 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class RateLimitException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + BraintrustServiceException("429: $body", cause) { + + override fun statusCode(): Int = 429 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RateLimitException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RateLimitException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(rateLimitException: RateLimitException) = apply { + headers = rateLimitException.headers + body = rateLimitException.body + cause = rateLimitException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class RateLimitException(headers: Headers, body: String, error: BraintrustError) : - BraintrustServiceException(429, headers, body, error) + /** + * Returns an immutable instance of [RateLimitException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RateLimitException = + RateLimitException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/UnauthorizedException.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/UnauthorizedException.kt index 57f9242f..55d60f4c 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/UnauthorizedException.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/UnauthorizedException.kt @@ -1,6 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class UnauthorizedException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + BraintrustServiceException("401: $body", cause) { + + override fun statusCode(): Int = 401 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UnauthorizedException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnauthorizedException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(unauthorizedException: UnauthorizedException) = apply { + headers = unauthorizedException.headers + body = unauthorizedException.body + cause = unauthorizedException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class UnauthorizedException(headers: Headers, body: String, error: BraintrustError) : - BraintrustServiceException(401, headers, body, error) + /** + * Returns an immutable instance of [UnauthorizedException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UnauthorizedException = + UnauthorizedException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/UnexpectedStatusCodeException.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/UnexpectedStatusCodeException.kt index 7aa10d9b..f463ecdd 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/UnexpectedStatusCodeException.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/UnexpectedStatusCodeException.kt @@ -1,10 +1,92 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class UnexpectedStatusCodeException +private constructor( + private val statusCode: Int, + private val headers: Headers, + private val body: JsonValue, + cause: Throwable?, +) : BraintrustServiceException("$statusCode: $body", cause) { + + override fun statusCode(): Int = statusCode + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [UnexpectedStatusCodeException]. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnexpectedStatusCodeException]. */ + class Builder internal constructor() { + + private var statusCode: Int? = null + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(unexpectedStatusCodeException: UnexpectedStatusCodeException) = apply { + statusCode = unexpectedStatusCodeException.statusCode + headers = unexpectedStatusCodeException.headers + body = unexpectedStatusCodeException.body + cause = unexpectedStatusCodeException.cause + } + + fun statusCode(statusCode: Int) = apply { this.statusCode = statusCode } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class UnexpectedStatusCodeException( - statusCode: Int, - headers: Headers, - body: String, - error: BraintrustError, -) : BraintrustServiceException(statusCode, headers, body, error) + /** + * Returns an immutable instance of [UnexpectedStatusCodeException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UnexpectedStatusCodeException = + UnexpectedStatusCodeException( + checkRequired("statusCode", statusCode), + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/UnprocessableEntityException.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/UnprocessableEntityException.kt index 6e216b4e..22101f46 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/UnprocessableEntityException.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/UnprocessableEntityException.kt @@ -1,6 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class UnprocessableEntityException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + BraintrustServiceException("422: $body", cause) { + + override fun statusCode(): Int = 422 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UnprocessableEntityException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnprocessableEntityException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(unprocessableEntityException: UnprocessableEntityException) = apply { + headers = unprocessableEntityException.headers + body = unprocessableEntityException.body + cause = unprocessableEntityException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class UnprocessableEntityException(headers: Headers, body: String, error: BraintrustError) : - BraintrustServiceException(422, headers, body, error) + /** + * Returns an immutable instance of [UnprocessableEntityException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UnprocessableEntityException = + UnprocessableEntityException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AISecret.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AISecret.kt index 1019fd7b..f5ad5a1b 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AISecret.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AISecret.kt @@ -6,9 +6,7 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -16,33 +14,42 @@ import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class AISecret -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("org_id") @ExcludeMissing private val orgId: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("preview_secret") - @ExcludeMissing - private val previewSecret: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonProperty("updated_at") - @ExcludeMissing - private val updatedAt: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val name: JsonField, + private val orgId: JsonField, + private val created: JsonField, + private val metadata: JsonField, + private val previewSecret: JsonField, + private val type: JsonField, + private val updatedAt: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("org_id") @ExcludeMissing orgId: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("preview_secret") + @ExcludeMissing + previewSecret: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("updated_at") + @ExcludeMissing + updatedAt: JsonField = JsonMissing.of(), + ) : this(id, name, orgId, created, metadata, previewSecret, type, updatedAt, mutableMapOf()) + /** * Unique identifier for the AI secret * @@ -73,26 +80,25 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun previewSecret(): Optional = - Optional.ofNullable(previewSecret.getNullable("preview_secret")) + fun previewSecret(): Optional = previewSecret.getOptional("preview_secret") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + fun type(): Optional = type.getOptional("type") /** * Date of last AI secret update @@ -100,8 +106,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [id]. @@ -163,27 +168,15 @@ private constructor( @ExcludeMissing fun _updatedAt(): JsonField = updatedAt + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AISecret = apply { - if (validated) { - return@apply - } - - id() - name() - orgId() - created() - metadata().ifPresent { it.validate() } - previewSecret() - type() - updatedAt() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -379,32 +372,63 @@ private constructor( previewSecret, type, updatedAt, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): AISecret = apply { + if (validated) { + return@apply + } + + id() + name() + orgId() + created() + metadata().ifPresent { it.validate() } + previewSecret() + type() + updatedAt() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (orgId.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (previewSecret.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + class Metadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -450,6 +474,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Acl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Acl.kt index 514087dd..34941085 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Acl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Acl.kt @@ -6,16 +6,14 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -30,41 +28,57 @@ import kotlin.jvm.optionals.getOrNull * To restrict a grant to a particular sub-object, you may specify `restrict_object_type` in the * ACL, as part of a direct permission grant or as part of a role. */ -@NoAutoDetect class Acl -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("_object_org_id") - @ExcludeMissing - private val _objectOrgId: JsonField = JsonMissing.of(), - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("group_id") - @ExcludeMissing - private val groupId: JsonField = JsonMissing.of(), - @JsonProperty("permission") - @ExcludeMissing - private val permission: JsonField = JsonMissing.of(), - @JsonProperty("restrict_object_type") - @ExcludeMissing - private val restrictObjectType: JsonField = JsonMissing.of(), - @JsonProperty("role_id") - @ExcludeMissing - private val roleId: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val _objectOrgId: JsonField, + private val objectId: JsonField, + private val objectType: JsonField, + private val created: JsonField, + private val groupId: JsonField, + private val permission: JsonField, + private val restrictObjectType: JsonField, + private val roleId: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("_object_org_id") + @ExcludeMissing + _objectOrgId: JsonField = JsonMissing.of(), + @JsonProperty("object_id") @ExcludeMissing objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("group_id") @ExcludeMissing groupId: JsonField = JsonMissing.of(), + @JsonProperty("permission") + @ExcludeMissing + permission: JsonField = JsonMissing.of(), + @JsonProperty("restrict_object_type") + @ExcludeMissing + restrictObjectType: JsonField = JsonMissing.of(), + @JsonProperty("role_id") @ExcludeMissing roleId: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this( + id, + _objectOrgId, + objectId, + objectType, + created, + groupId, + permission, + restrictObjectType, + roleId, + userId, + mutableMapOf(), + ) + /** * Unique identifier for the acl * @@ -103,7 +117,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Id of the group the ACL applies to. Exactly one of `user_id` and `group_id` will be provided @@ -111,7 +125,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun groupId(): Optional = Optional.ofNullable(groupId.getNullable("group_id")) + fun groupId(): Optional = groupId.getOptional("group_id") /** * Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided @@ -119,8 +133,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun permission(): Optional = - Optional.ofNullable(permission.getNullable("permission")) + fun permission(): Optional = permission.getOptional("permission") /** * When setting a permission directly, optionally restricts the permission grant to just the @@ -130,7 +143,7 @@ private constructor( * server responded with an unexpected value). */ fun restrictObjectType(): Optional = - Optional.ofNullable(restrictObjectType.getNullable("restrict_object_type")) + restrictObjectType.getOptional("restrict_object_type") /** * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be provided @@ -138,7 +151,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun roleId(): Optional = Optional.ofNullable(roleId.getNullable("role_id")) + fun roleId(): Optional = roleId.getOptional("role_id") /** * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be provided @@ -146,7 +159,7 @@ private constructor( * @throws BraintrustInvalidDataException 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 [id]. @@ -227,29 +240,15 @@ private constructor( */ @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 = additionalProperties - - private var validated: Boolean = false - - fun validate(): Acl = apply { - if (validated) { - return@apply - } - - id() - _objectOrgId() - objectId() - objectType() - created() - groupId() - permission() - restrictObjectType() - roleId() - userId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -499,10 +498,56 @@ private constructor( restrictObjectType, roleId, userId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Acl = apply { + if (validated) { + return@apply + } + + id() + _objectOrgId() + objectId() + objectType().validate() + created() + groupId() + permission().ifPresent { it.validate() } + restrictObjectType().ifPresent { it.validate() } + roleId() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (_objectOrgId.asKnown().isPresent) 1 else 0) + + (if (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (groupId.asKnown().isPresent) 1 else 0) + + (permission.asKnown().getOrNull()?.validity() ?: 0) + + (restrictObjectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (roleId.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclBatchUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclBatchUpdateParams.kt index de92b67f..3276e25a 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclBatchUpdateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclBatchUpdateParams.kt @@ -6,19 +6,18 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -84,241 +83,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("add_acls") - @ExcludeMissing - private val addAcls: JsonField> = JsonMissing.of(), - @JsonProperty("remove_acls") - @ExcludeMissing - private val removeAcls: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * An ACL grants a certain permission or role to a certain user or group on an object. - * - * ACLs are inherited across the object hierarchy. So for example, if a user has read - * permissions on a project, they will also have read permissions on any experiment, - * dataset, etc. created within that project. - * - * To restrict a grant to a particular sub-object, you may specify `restrict_object_type` in - * the ACL, as part of a direct permission grant or as part of a role. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun addAcls(): Optional> = Optional.ofNullable(addAcls.getNullable("add_acls")) - - /** - * An ACL grants a certain permission or role to a certain user or group on an object. - * - * ACLs are inherited across the object hierarchy. So for example, if a user has read - * permissions on a project, they will also have read permissions on any experiment, - * dataset, etc. created within that project. - * - * To restrict a grant to a particular sub-object, you may specify `restrict_object_type` in - * the ACL, as part of a direct permission grant or as part of a role. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun removeAcls(): Optional> = - Optional.ofNullable(removeAcls.getNullable("remove_acls")) - - /** - * Returns the raw JSON value of [addAcls]. - * - * Unlike [addAcls], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("add_acls") @ExcludeMissing fun _addAcls(): JsonField> = addAcls - - /** - * Returns the raw JSON value of [removeAcls]. - * - * Unlike [removeAcls], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("remove_acls") - @ExcludeMissing - fun _removeAcls(): JsonField> = removeAcls - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - addAcls().ifPresent { it.forEach { it.validate() } } - removeAcls().ifPresent { it.forEach { it.validate() } } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Body]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var addAcls: JsonField>? = null - private var removeAcls: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - addAcls = body.addAcls.map { it.toMutableList() } - removeAcls = body.removeAcls.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** - * An ACL grants a certain permission or role to a certain user or group on an object. - * - * ACLs are inherited across the object hierarchy. So for example, if a user has read - * permissions on a project, they will also have read permissions on any experiment, - * dataset, etc. created within that project. - * - * To restrict a grant to a particular sub-object, you may specify - * `restrict_object_type` in the ACL, as part of a direct permission grant or as part of - * a role. - */ - fun addAcls(addAcls: List?) = addAcls(JsonField.ofNullable(addAcls)) - - /** Alias for calling [Builder.addAcls] with `addAcls.orElse(null)`. */ - fun addAcls(addAcls: Optional>) = addAcls(addAcls.getOrNull()) - - /** - * Sets [Builder.addAcls] to an arbitrary JSON value. - * - * You should usually call [Builder.addAcls] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun addAcls(addAcls: JsonField>) = apply { - this.addAcls = addAcls.map { it.toMutableList() } - } - - /** - * Adds a single [AddAcl] to [addAcls]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addAddAcl(addAcl: AddAcl) = apply { - addAcls = - (addAcls ?: JsonField.of(mutableListOf())).also { - checkKnown("addAcls", it).add(addAcl) - } - } - - /** - * An ACL grants a certain permission or role to a certain user or group on an object. - * - * ACLs are inherited across the object hierarchy. So for example, if a user has read - * permissions on a project, they will also have read permissions on any experiment, - * dataset, etc. created within that project. - * - * To restrict a grant to a particular sub-object, you may specify - * `restrict_object_type` in the ACL, as part of a direct permission grant or as part of - * a role. - */ - fun removeAcls(removeAcls: List?) = - removeAcls(JsonField.ofNullable(removeAcls)) - - /** Alias for calling [Builder.removeAcls] with `removeAcls.orElse(null)`. */ - fun removeAcls(removeAcls: Optional>) = - removeAcls(removeAcls.getOrNull()) - - /** - * Sets [Builder.removeAcls] to an arbitrary JSON value. - * - * You should usually call [Builder.removeAcls] with a well-typed `List` - * value instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun removeAcls(removeAcls: JsonField>) = apply { - this.removeAcls = removeAcls.map { it.toMutableList() } - } - - /** - * Adds a single [RemoveAcl] to [removeAcls]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addRemoveAcl(removeAcl: RemoveAcl) = apply { - removeAcls = - (removeAcls ?: JsonField.of(mutableListOf())).also { - checkKnown("removeAcls", it).add(removeAcl) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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. - */ - fun build(): Body = - Body( - (addAcls ?: JsonMissing.of()).map { it.toImmutable() }, - (removeAcls ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && addAcls == other.addAcls && removeAcls == other.removeAcls && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(addAcls, removeAcls, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{addAcls=$addAcls, removeAcls=$removeAcls, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -330,7 +94,6 @@ private constructor( } /** A builder for [AclBatchUpdateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -344,6 +107,16 @@ private constructor( additionalQueryParams = aclBatchUpdateParams.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: + * - [addAcls] + * - [removeAcls] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** * An ACL grants a certain permission or role to a certain user or group on an object. * @@ -445,97 +218,359 @@ private constructor( additionalHeaders.put(name, values) } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + 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 [AclBatchUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AclBatchUpdateParams = + AclBatchUpdateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val addAcls: JsonField>, + private val removeAcls: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("add_acls") + @ExcludeMissing + addAcls: JsonField> = JsonMissing.of(), + @JsonProperty("remove_acls") + @ExcludeMissing + removeAcls: JsonField> = JsonMissing.of(), + ) : this(addAcls, removeAcls, mutableMapOf()) + + /** + * An ACL grants a certain permission or role to a certain user or group on an object. + * + * ACLs are inherited across the object hierarchy. So for example, if a user has read + * permissions on a project, they will also have read permissions on any experiment, + * dataset, etc. created within that project. + * + * To restrict a grant to a particular sub-object, you may specify `restrict_object_type` in + * the ACL, as part of a direct permission grant or as part of a role. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun addAcls(): Optional> = addAcls.getOptional("add_acls") + + /** + * An ACL grants a certain permission or role to a certain user or group on an object. + * + * ACLs are inherited across the object hierarchy. So for example, if a user has read + * permissions on a project, they will also have read permissions on any experiment, + * dataset, etc. created within that project. + * + * To restrict a grant to a particular sub-object, you may specify `restrict_object_type` in + * the ACL, as part of a direct permission grant or as part of a role. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun removeAcls(): Optional> = removeAcls.getOptional("remove_acls") + + /** + * Returns the raw JSON value of [addAcls]. + * + * Unlike [addAcls], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("add_acls") @ExcludeMissing fun _addAcls(): JsonField> = addAcls + + /** + * Returns the raw JSON value of [removeAcls]. + * + * Unlike [removeAcls], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("remove_acls") + @ExcludeMissing + fun _removeAcls(): JsonField> = removeAcls + + @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]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var addAcls: JsonField>? = null + private var removeAcls: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + addAcls = body.addAcls.map { it.toMutableList() } + removeAcls = body.removeAcls.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** + * An ACL grants a certain permission or role to a certain user or group on an object. + * + * ACLs are inherited across the object hierarchy. So for example, if a user has read + * permissions on a project, they will also have read permissions on any experiment, + * dataset, etc. created within that project. + * + * To restrict a grant to a particular sub-object, you may specify + * `restrict_object_type` in the ACL, as part of a direct permission grant or as part of + * a role. + */ + fun addAcls(addAcls: List?) = addAcls(JsonField.ofNullable(addAcls)) + + /** Alias for calling [Builder.addAcls] with `addAcls.orElse(null)`. */ + fun addAcls(addAcls: Optional>) = addAcls(addAcls.getOrNull()) + + /** + * Sets [Builder.addAcls] to an arbitrary JSON value. + * + * You should usually call [Builder.addAcls] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun addAcls(addAcls: JsonField>) = apply { + this.addAcls = addAcls.map { it.toMutableList() } + } + + /** + * Adds a single [AddAcl] to [addAcls]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAddAcl(addAcl: AddAcl) = apply { + addAcls = + (addAcls ?: JsonField.of(mutableListOf())).also { + checkKnown("addAcls", it).add(addAcl) + } + } + + /** + * An ACL grants a certain permission or role to a certain user or group on an object. + * + * ACLs are inherited across the object hierarchy. So for example, if a user has read + * permissions on a project, they will also have read permissions on any experiment, + * dataset, etc. created within that project. + * + * To restrict a grant to a particular sub-object, you may specify + * `restrict_object_type` in the ACL, as part of a direct permission grant or as part of + * a role. + */ + fun removeAcls(removeAcls: List?) = + removeAcls(JsonField.ofNullable(removeAcls)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.removeAcls] with `removeAcls.orElse(null)`. */ + fun removeAcls(removeAcls: Optional>) = + removeAcls(removeAcls.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.removeAcls] to an arbitrary JSON value. + * + * You should usually call [Builder.removeAcls] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun removeAcls(removeAcls: JsonField>) = apply { + this.removeAcls = removeAcls.map { it.toMutableList() } + } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** + * Adds a single [RemoveAcl] to [removeAcls]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addRemoveAcl(removeAcl: RemoveAcl) = apply { + removeAcls = + (removeAcls ?: JsonField.of(mutableListOf())).also { + checkKnown("removeAcls", it).add(removeAcl) + } + } - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body( + (addAcls ?: JsonMissing.of()).map { it.toImmutable() }, + (removeAcls ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + private var validated: Boolean = false - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun validate(): Body = apply { + if (validated) { + return@apply + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) + addAcls().ifPresent { it.forEach { it.validate() } } + removeAcls().ifPresent { it.forEach { it.validate() } } + validated = true } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (addAcls.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (removeAcls.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + return /* spotless:off */ other is Body && addAcls == other.addAcls && removeAcls == other.removeAcls && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(addAcls, removeAcls, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [AclBatchUpdateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): AclBatchUpdateParams = - AclBatchUpdateParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{addAcls=$addAcls, removeAcls=$removeAcls, additionalProperties=$additionalProperties}" } /** @@ -548,35 +583,46 @@ private constructor( * To restrict a grant to a particular sub-object, you may specify `restrict_object_type` in the * ACL, as part of a direct permission grant or as part of a role. */ - @NoAutoDetect class AddAcl - @JsonCreator private constructor( - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("group_id") - @ExcludeMissing - private val groupId: JsonField = JsonMissing.of(), - @JsonProperty("permission") - @ExcludeMissing - private val permission: JsonField = JsonMissing.of(), - @JsonProperty("restrict_object_type") - @ExcludeMissing - private val restrictObjectType: JsonField = JsonMissing.of(), - @JsonProperty("role_id") - @ExcludeMissing - private val roleId: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val objectId: JsonField, + private val objectType: JsonField, + private val groupId: JsonField, + private val permission: JsonField, + private val restrictObjectType: JsonField, + private val roleId: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("object_id") + @ExcludeMissing + objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("group_id") @ExcludeMissing groupId: JsonField = JsonMissing.of(), + @JsonProperty("permission") + @ExcludeMissing + permission: JsonField = JsonMissing.of(), + @JsonProperty("restrict_object_type") + @ExcludeMissing + restrictObjectType: JsonField = JsonMissing.of(), + @JsonProperty("role_id") @ExcludeMissing roleId: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this( + objectId, + objectType, + groupId, + permission, + restrictObjectType, + roleId, + userId, + mutableMapOf(), + ) + /** * The id of the object the ACL applies to * @@ -600,7 +646,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun groupId(): Optional = Optional.ofNullable(groupId.getNullable("group_id")) + fun groupId(): Optional = groupId.getOptional("group_id") /** * Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided @@ -608,8 +654,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun permission(): Optional = - Optional.ofNullable(permission.getNullable("permission")) + fun permission(): Optional = permission.getOptional("permission") /** * When setting a permission directly, optionally restricts the permission grant to just the @@ -619,7 +664,7 @@ private constructor( * the server responded with an unexpected value). */ fun restrictObjectType(): Optional = - Optional.ofNullable(restrictObjectType.getNullable("restrict_object_type")) + restrictObjectType.getOptional("restrict_object_type") /** * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be provided @@ -627,7 +672,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun roleId(): Optional = Optional.ofNullable(roleId.getNullable("role_id")) + fun roleId(): Optional = roleId.getOptional("role_id") /** * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be @@ -636,7 +681,7 @@ private constructor( * @throws BraintrustInvalidDataException 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 [objectId]. @@ -694,26 +739,15 @@ private constructor( */ @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 = additionalProperties - - private var validated: Boolean = false - - fun validate(): AddAcl = apply { - if (validated) { - return@apply - } - - objectId() - objectType() - groupId() - permission() - restrictObjectType() - roleId() - userId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -920,10 +954,51 @@ private constructor( restrictObjectType, roleId, userId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): AddAcl = apply { + if (validated) { + return@apply + } + + objectId() + objectType().validate() + groupId() + permission().ifPresent { it.validate() } + restrictObjectType().ifPresent { it.validate() } + roleId() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (groupId.asKnown().isPresent) 1 else 0) + + (permission.asKnown().getOrNull()?.validity() ?: 0) + + (restrictObjectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (roleId.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -952,35 +1027,46 @@ private constructor( * To restrict a grant to a particular sub-object, you may specify `restrict_object_type` in the * ACL, as part of a direct permission grant or as part of a role. */ - @NoAutoDetect class RemoveAcl - @JsonCreator private constructor( - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("group_id") - @ExcludeMissing - private val groupId: JsonField = JsonMissing.of(), - @JsonProperty("permission") - @ExcludeMissing - private val permission: JsonField = JsonMissing.of(), - @JsonProperty("restrict_object_type") - @ExcludeMissing - private val restrictObjectType: JsonField = JsonMissing.of(), - @JsonProperty("role_id") - @ExcludeMissing - private val roleId: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val objectId: JsonField, + private val objectType: JsonField, + private val groupId: JsonField, + private val permission: JsonField, + private val restrictObjectType: JsonField, + private val roleId: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("object_id") + @ExcludeMissing + objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("group_id") @ExcludeMissing groupId: JsonField = JsonMissing.of(), + @JsonProperty("permission") + @ExcludeMissing + permission: JsonField = JsonMissing.of(), + @JsonProperty("restrict_object_type") + @ExcludeMissing + restrictObjectType: JsonField = JsonMissing.of(), + @JsonProperty("role_id") @ExcludeMissing roleId: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this( + objectId, + objectType, + groupId, + permission, + restrictObjectType, + roleId, + userId, + mutableMapOf(), + ) + /** * The id of the object the ACL applies to * @@ -1004,7 +1090,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun groupId(): Optional = Optional.ofNullable(groupId.getNullable("group_id")) + fun groupId(): Optional = groupId.getOptional("group_id") /** * Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided @@ -1012,8 +1098,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun permission(): Optional = - Optional.ofNullable(permission.getNullable("permission")) + fun permission(): Optional = permission.getOptional("permission") /** * When setting a permission directly, optionally restricts the permission grant to just the @@ -1023,7 +1108,7 @@ private constructor( * the server responded with an unexpected value). */ fun restrictObjectType(): Optional = - Optional.ofNullable(restrictObjectType.getNullable("restrict_object_type")) + restrictObjectType.getOptional("restrict_object_type") /** * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be provided @@ -1031,7 +1116,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun roleId(): Optional = Optional.ofNullable(roleId.getNullable("role_id")) + fun roleId(): Optional = roleId.getOptional("role_id") /** * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be @@ -1040,7 +1125,7 @@ private constructor( * @throws BraintrustInvalidDataException 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 [objectId]. @@ -1098,26 +1183,15 @@ private constructor( */ @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 = additionalProperties - - private var validated: Boolean = false - - fun validate(): RemoveAcl = apply { - if (validated) { - return@apply - } - - objectId() - objectType() - groupId() - permission() - restrictObjectType() - roleId() - userId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1324,10 +1398,51 @@ private constructor( restrictObjectType, roleId, userId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): RemoveAcl = apply { + if (validated) { + return@apply + } + + objectId() + objectType().validate() + groupId() + permission().ifPresent { it.validate() } + restrictObjectType().ifPresent { it.validate() } + roleId() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (groupId.asKnown().isPresent) 1 else 0) + + (permission.asKnown().getOrNull()?.validity() ?: 0) + + (restrictObjectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (roleId.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclBatchUpdateResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclBatchUpdateResponse.kt index ee549d63..901575b1 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclBatchUpdateResponse.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclBatchUpdateResponse.kt @@ -6,31 +6,35 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 kotlin.jvm.optionals.getOrNull -@NoAutoDetect class AclBatchUpdateResponse -@JsonCreator private constructor( - @JsonProperty("added_acls") - @ExcludeMissing - private val addedAcls: JsonField> = JsonMissing.of(), - @JsonProperty("removed_acls") - @ExcludeMissing - private val removedAcls: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val addedAcls: JsonField>, + private val removedAcls: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("added_acls") + @ExcludeMissing + addedAcls: JsonField> = JsonMissing.of(), + @JsonProperty("removed_acls") + @ExcludeMissing + removedAcls: JsonField> = JsonMissing.of(), + ) : this(addedAcls, removedAcls, mutableMapOf()) + /** * An ACL grants a certain permission or role to a certain user or group on an object. * @@ -77,21 +81,15 @@ private constructor( @ExcludeMissing fun _removedAcls(): JsonField> = removedAcls + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AclBatchUpdateResponse = apply { - if (validated) { - return@apply - } - - addedAcls().forEach { it.validate() } - removedAcls().forEach { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -229,10 +227,40 @@ private constructor( AclBatchUpdateResponse( checkRequired("addedAcls", addedAcls).map { it.toImmutable() }, checkRequired("removedAcls", removedAcls).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): AclBatchUpdateResponse = apply { + if (validated) { + return@apply + } + + addedAcls().forEach { it.validate() } + removedAcls().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (addedAcls.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (removedAcls.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclCreateParams.kt index 27d4477a..88196664 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclCreateParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -146,692 +144,745 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun toBuilder() = Builder().from(this) - /** - * An ACL grants a certain permission or role to a certain user or group on an object. - * - * ACLs are inherited across the object hierarchy. So for example, if a user has read - * permissions on a project, they will also have read permissions on any experiment, dataset, - * etc. created within that project. - * - * To restrict a grant to a particular sub-object, you may specify `restrict_object_type` in the - * ACL, as part of a direct permission grant or as part of a role. - */ - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("group_id") - @ExcludeMissing - private val groupId: JsonField = JsonMissing.of(), - @JsonProperty("permission") - @ExcludeMissing - private val permission: JsonField = JsonMissing.of(), - @JsonProperty("restrict_object_type") - @ExcludeMissing - private val restrictObjectType: JsonField = JsonMissing.of(), - @JsonProperty("role_id") - @ExcludeMissing - private val roleId: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + companion object { /** - * The id of the object the ACL applies to + * Returns a mutable builder for constructing an instance of [AclCreateParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` */ - fun objectId(): String = objectId.getRequired("object_id") + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AclCreateParams]. */ + 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(aclCreateParams: AclCreateParams) = apply { + body = aclCreateParams.body.toBuilder() + additionalHeaders = aclCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = aclCreateParams.additionalQueryParams.toBuilder() + } /** - * The object type that the ACL applies to + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * 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: + * - [objectId] + * - [objectType] + * - [groupId] + * - [permission] + * - [restrictObjectType] + * - etc. */ - fun objectType(): AclObjectType = objectType.getRequired("object_type") + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** The id of the object the ACL applies to */ + fun objectId(objectId: String) = apply { body.objectId(objectId) } /** - * Id of the group the ACL applies to. Exactly one of `user_id` and `group_id` will be - * provided + * Sets [Builder.objectId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.objectId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - fun groupId(): Optional = Optional.ofNullable(groupId.getNullable("group_id")) + fun objectId(objectId: JsonField) = apply { body.objectId(objectId) } + + /** The object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = apply { body.objectType(objectType) } /** - * Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided + * Sets [Builder.objectType] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun permission(): Optional = - Optional.ofNullable(permission.getNullable("permission")) + fun objectType(objectType: JsonField) = apply { body.objectType(objectType) } /** - * When setting a permission directly, optionally restricts the permission grant to just the - * specified object type. Cannot be set alongside a `role_id`. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * Id of the group the ACL applies to. Exactly one of `user_id` and `group_id` will be + * provided */ - fun restrictObjectType(): Optional = - Optional.ofNullable(restrictObjectType.getNullable("restrict_object_type")) + fun groupId(groupId: String?) = apply { body.groupId(groupId) } + + /** Alias for calling [Builder.groupId] with `groupId.orElse(null)`. */ + fun groupId(groupId: Optional) = groupId(groupId.getOrNull()) /** - * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be provided + * Sets [Builder.groupId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.groupId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - fun roleId(): Optional = Optional.ofNullable(roleId.getNullable("role_id")) + fun groupId(groupId: JsonField) = apply { body.groupId(groupId) } + + /** Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided */ + fun permission(permission: Permission?) = apply { body.permission(permission) } + + /** Alias for calling [Builder.permission] with `permission.orElse(null)`. */ + fun permission(permission: Optional) = permission(permission.getOrNull()) /** - * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be - * provided + * Sets [Builder.permission] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.permission] with a well-typed [Permission] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) + fun permission(permission: JsonField) = apply { body.permission(permission) } /** - * Returns the raw JSON value of [objectId]. - * - * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. + * When setting a permission directly, optionally restricts the permission grant to just the + * specified object type. Cannot be set alongside a `role_id`. */ - @JsonProperty("object_id") @ExcludeMissing fun _objectId(): JsonField = objectId + fun restrictObjectType(restrictObjectType: AclObjectType?) = apply { + body.restrictObjectType(restrictObjectType) + } /** - * Returns the raw JSON value of [objectType]. - * - * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + * Alias for calling [Builder.restrictObjectType] with `restrictObjectType.orElse(null)`. */ - @JsonProperty("object_type") - @ExcludeMissing - fun _objectType(): JsonField = objectType + fun restrictObjectType(restrictObjectType: Optional) = + restrictObjectType(restrictObjectType.getOrNull()) /** - * Returns the raw JSON value of [groupId]. + * Sets [Builder.restrictObjectType] to an arbitrary JSON value. * - * Unlike [groupId], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.restrictObjectType] with a well-typed [AclObjectType] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. */ - @JsonProperty("group_id") @ExcludeMissing fun _groupId(): JsonField = groupId + fun restrictObjectType(restrictObjectType: JsonField) = apply { + body.restrictObjectType(restrictObjectType) + } /** - * Returns the raw JSON value of [permission]. - * - * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. + * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be provided */ - @JsonProperty("permission") - @ExcludeMissing - fun _permission(): JsonField = permission + fun roleId(roleId: String?) = apply { body.roleId(roleId) } + + /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ + fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) /** - * Returns the raw JSON value of [restrictObjectType]. + * Sets [Builder.roleId] to an arbitrary JSON value. * - * Unlike [restrictObjectType], this method doesn't throw if the JSON field has an - * unexpected type. + * You should usually call [Builder.roleId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("restrict_object_type") - @ExcludeMissing - fun _restrictObjectType(): JsonField = restrictObjectType + fun roleId(roleId: JsonField) = apply { body.roleId(roleId) } /** - * Returns the raw JSON value of [roleId]. - * - * Unlike [roleId], this method doesn't throw if the JSON field has an unexpected type. + * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be + * provided */ - @JsonProperty("role_id") @ExcludeMissing fun _roleId(): JsonField = roleId + fun userId(userId: String?) = apply { body.userId(userId) } + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) /** - * Returns the raw JSON value of [userId]. + * Sets [Builder.userId] to an arbitrary JSON value. * - * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + fun userId(userId: JsonField) = apply { body.userId(userId) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var validated: Boolean = false + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - fun validate(): Body = apply { - if (validated) { - return@apply + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - objectId() - objectType() - groupId() - permission() - restrictObjectType() - roleId() - userId() - validated = true - } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun toBuilder() = Builder().from(this) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - companion object { + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .objectId() - * .objectType() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - private var objectId: JsonField? = null - private var objectType: JsonField? = null - private var groupId: JsonField = JsonMissing.of() - private var permission: JsonField = JsonMissing.of() - private var restrictObjectType: JsonField = JsonMissing.of() - private var roleId: JsonField = JsonMissing.of() - private var userId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - @JvmSynthetic - internal fun from(body: Body) = apply { - objectId = body.objectId - objectType = body.objectType - groupId = body.groupId - permission = body.permission - restrictObjectType = body.restrictObjectType - roleId = body.roleId - userId = body.userId - additionalProperties = body.additionalProperties.toMutableMap() - } + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** The id of the object the ACL applies to */ - fun objectId(objectId: String) = objectId(JsonField.of(objectId)) - - /** - * Sets [Builder.objectId] to an arbitrary JSON value. - * - * You should usually call [Builder.objectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun objectId(objectId: JsonField) = apply { this.objectId = objectId } - - /** The object type that the ACL applies to */ - fun objectType(objectType: AclObjectType) = objectType(JsonField.of(objectType)) - - /** - * Sets [Builder.objectType] to an arbitrary JSON value. - * - * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun objectType(objectType: JsonField) = apply { - this.objectType = objectType - } - - /** - * Id of the group the ACL applies to. Exactly one of `user_id` and `group_id` will be - * provided - */ - fun groupId(groupId: String?) = groupId(JsonField.ofNullable(groupId)) - - /** Alias for calling [Builder.groupId] with `groupId.orElse(null)`. */ - fun groupId(groupId: Optional) = groupId(groupId.getOrNull()) - - /** - * Sets [Builder.groupId] to an arbitrary JSON value. - * - * You should usually call [Builder.groupId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun groupId(groupId: JsonField) = apply { this.groupId = groupId } - - /** - * Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided - */ - fun permission(permission: Permission?) = permission(JsonField.ofNullable(permission)) - - /** Alias for calling [Builder.permission] with `permission.orElse(null)`. */ - fun permission(permission: Optional) = permission(permission.getOrNull()) - - /** - * Sets [Builder.permission] to an arbitrary JSON value. - * - * You should usually call [Builder.permission] with a well-typed [Permission] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun permission(permission: JsonField) = apply { - this.permission = permission - } - - /** - * When setting a permission directly, optionally restricts the permission grant to just - * the specified object type. Cannot be set alongside a `role_id`. - */ - fun restrictObjectType(restrictObjectType: AclObjectType?) = - restrictObjectType(JsonField.ofNullable(restrictObjectType)) - - /** - * Alias for calling [Builder.restrictObjectType] with - * `restrictObjectType.orElse(null)`. - */ - fun restrictObjectType(restrictObjectType: Optional) = - restrictObjectType(restrictObjectType.getOrNull()) - - /** - * Sets [Builder.restrictObjectType] to an arbitrary JSON value. - * - * You should usually call [Builder.restrictObjectType] with a well-typed - * [AclObjectType] value instead. This method is primarily for setting the field to an - * undocumented or not yet supported value. - */ - fun restrictObjectType(restrictObjectType: JsonField) = apply { - this.restrictObjectType = restrictObjectType - } - - /** - * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be - * provided - */ - fun roleId(roleId: String?) = roleId(JsonField.ofNullable(roleId)) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ - fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * Sets [Builder.roleId] to an arbitrary JSON value. - * - * You should usually call [Builder.roleId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun roleId(roleId: JsonField) = apply { this.roleId = roleId } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** - * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be - * provided - */ - fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ - fun userId(userId: Optional) = userId(userId.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * 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 removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .objectId() - * .objectType() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("objectId", objectId), - checkRequired("objectType", objectType), - groupId, - permission, - restrictObjectType, - roleId, - userId, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && objectId == other.objectId && objectType == other.objectType && groupId == other.groupId && permission == other.permission && restrictObjectType == other.restrictObjectType && roleId == other.roleId && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(objectId, objectType, groupId, permission, restrictObjectType, roleId, userId, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{objectId=$objectId, objectType=$objectType, groupId=$groupId, permission=$permission, restrictObjectType=$restrictObjectType, roleId=$roleId, userId=$userId, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [AclCreateParams]. + * Returns an immutable instance of [AclCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java * .objectId() * .objectType() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): AclCreateParams = + AclCreateParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) } - /** A builder for [AclCreateParams]. */ - @NoAutoDetect - class Builder internal constructor() { + fun _body(): Body = body - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + override fun _headers(): Headers = additionalHeaders - @JvmSynthetic - internal fun from(aclCreateParams: AclCreateParams) = apply { - body = aclCreateParams.body.toBuilder() - additionalHeaders = aclCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = aclCreateParams.additionalQueryParams.toBuilder() - } + override fun _queryParams(): QueryParams = additionalQueryParams - /** The id of the object the ACL applies to */ - fun objectId(objectId: String) = apply { body.objectId(objectId) } + /** + * An ACL grants a certain permission or role to a certain user or group on an object. + * + * ACLs are inherited across the object hierarchy. So for example, if a user has read + * permissions on a project, they will also have read permissions on any experiment, dataset, + * etc. created within that project. + * + * To restrict a grant to a particular sub-object, you may specify `restrict_object_type` in the + * ACL, as part of a direct permission grant or as part of a role. + */ + class Body + private constructor( + private val objectId: JsonField, + private val objectType: JsonField, + private val groupId: JsonField, + private val permission: JsonField, + private val restrictObjectType: JsonField, + private val roleId: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("object_id") + @ExcludeMissing + objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("group_id") @ExcludeMissing groupId: JsonField = JsonMissing.of(), + @JsonProperty("permission") + @ExcludeMissing + permission: JsonField = JsonMissing.of(), + @JsonProperty("restrict_object_type") + @ExcludeMissing + restrictObjectType: JsonField = JsonMissing.of(), + @JsonProperty("role_id") @ExcludeMissing roleId: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this( + objectId, + objectType, + groupId, + permission, + restrictObjectType, + roleId, + userId, + mutableMapOf(), + ) /** - * Sets [Builder.objectId] to an arbitrary JSON value. + * The id of the object the ACL applies to * - * You should usually call [Builder.objectId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException 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 objectId(objectId: JsonField) = apply { body.objectId(objectId) } - - /** The object type that the ACL applies to */ - fun objectType(objectType: AclObjectType) = apply { body.objectType(objectType) } + fun objectId(): String = objectId.getRequired("object_id") /** - * Sets [Builder.objectType] to an arbitrary JSON value. + * The object type that the ACL applies to * - * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException 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 objectType(objectType: JsonField) = apply { body.objectType(objectType) } + fun objectType(): AclObjectType = objectType.getRequired("object_type") /** * Id of the group the ACL applies to. Exactly one of `user_id` and `group_id` will be * provided + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun groupId(groupId: String?) = apply { body.groupId(groupId) } - - /** Alias for calling [Builder.groupId] with `groupId.orElse(null)`. */ - fun groupId(groupId: Optional) = groupId(groupId.getOrNull()) + fun groupId(): Optional = groupId.getOptional("group_id") /** - * Sets [Builder.groupId] to an arbitrary JSON value. + * Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided * - * You should usually call [Builder.groupId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun groupId(groupId: JsonField) = apply { body.groupId(groupId) } - - /** Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided */ - fun permission(permission: Permission?) = apply { body.permission(permission) } - - /** Alias for calling [Builder.permission] with `permission.orElse(null)`. */ - fun permission(permission: Optional) = permission(permission.getOrNull()) + fun permission(): Optional = permission.getOptional("permission") /** - * Sets [Builder.permission] to an arbitrary JSON value. + * When setting a permission directly, optionally restricts the permission grant to just the + * specified object type. Cannot be set alongside a `role_id`. * - * You should usually call [Builder.permission] with a well-typed [Permission] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun permission(permission: JsonField) = apply { body.permission(permission) } + fun restrictObjectType(): Optional = + restrictObjectType.getOptional("restrict_object_type") /** - * When setting a permission directly, optionally restricts the permission grant to just the - * specified object type. Cannot be set alongside a `role_id`. + * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be provided + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun restrictObjectType(restrictObjectType: AclObjectType?) = apply { - body.restrictObjectType(restrictObjectType) - } + fun roleId(): Optional = roleId.getOptional("role_id") /** - * Alias for calling [Builder.restrictObjectType] with `restrictObjectType.orElse(null)`. + * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be + * provided + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun restrictObjectType(restrictObjectType: Optional) = - restrictObjectType(restrictObjectType.getOrNull()) + fun userId(): Optional = userId.getOptional("user_id") /** - * Sets [Builder.restrictObjectType] to an arbitrary JSON value. + * Returns the raw JSON value of [objectId]. * - * You should usually call [Builder.restrictObjectType] with a well-typed [AclObjectType] - * value instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. + * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. */ - fun restrictObjectType(restrictObjectType: JsonField) = apply { - body.restrictObjectType(restrictObjectType) - } + @JsonProperty("object_id") @ExcludeMissing fun _objectId(): JsonField = objectId /** - * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be provided + * Returns the raw JSON value of [objectType]. + * + * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. */ - fun roleId(roleId: String?) = apply { body.roleId(roleId) } + @JsonProperty("object_type") + @ExcludeMissing + fun _objectType(): JsonField = objectType - /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ - fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) + /** + * Returns the raw JSON value of [groupId]. + * + * Unlike [groupId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("group_id") @ExcludeMissing fun _groupId(): JsonField = groupId /** - * Sets [Builder.roleId] to an arbitrary JSON value. + * Returns the raw JSON value of [permission]. * - * You should usually call [Builder.roleId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. */ - fun roleId(roleId: JsonField) = apply { body.roleId(roleId) } + @JsonProperty("permission") + @ExcludeMissing + fun _permission(): JsonField = permission /** - * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be - * provided + * Returns the raw JSON value of [restrictObjectType]. + * + * Unlike [restrictObjectType], this method doesn't throw if the JSON field has an + * unexpected type. */ - fun userId(userId: String?) = apply { body.userId(userId) } + @JsonProperty("restrict_object_type") + @ExcludeMissing + fun _restrictObjectType(): JsonField = restrictObjectType - /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ - fun userId(userId: Optional) = userId(userId.getOrNull()) + /** + * Returns the raw JSON value of [roleId]. + * + * Unlike [roleId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("role_id") @ExcludeMissing fun _roleId(): JsonField = roleId /** - * Sets [Builder.userId] to an arbitrary JSON value. + * Returns the raw JSON value of [userId]. * - * 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. + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. */ - fun userId(userId: JsonField) = apply { body.userId(userId) } + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) + @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 + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var objectId: JsonField? = null + private var objectType: JsonField? = null + private var groupId: JsonField = JsonMissing.of() + private var permission: JsonField = JsonMissing.of() + private var restrictObjectType: JsonField = JsonMissing.of() + private var roleId: JsonField = JsonMissing.of() + private var userId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + objectId = body.objectId + objectType = body.objectType + groupId = body.groupId + permission = body.permission + restrictObjectType = body.restrictObjectType + roleId = body.roleId + userId = body.userId + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** The id of the object the ACL applies to */ + fun objectId(objectId: String) = objectId(JsonField.of(objectId)) + + /** + * Sets [Builder.objectId] to an arbitrary JSON value. + * + * You should usually call [Builder.objectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectId(objectId: JsonField) = apply { this.objectId = objectId } + + /** The object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = objectType(JsonField.of(objectType)) - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) + /** + * Sets [Builder.objectType] to an arbitrary JSON value. + * + * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectType(objectType: JsonField) = apply { + this.objectType = objectType } - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** + * Id of the group the ACL applies to. Exactly one of `user_id` and `group_id` will be + * provided + */ + fun groupId(groupId: String?) = groupId(JsonField.ofNullable(groupId)) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** Alias for calling [Builder.groupId] with `groupId.orElse(null)`. */ + fun groupId(groupId: Optional) = groupId(groupId.getOrNull()) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Sets [Builder.groupId] to an arbitrary JSON value. + * + * You should usually call [Builder.groupId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun groupId(groupId: JsonField) = apply { this.groupId = groupId } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided + */ + fun permission(permission: Permission?) = permission(JsonField.ofNullable(permission)) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** Alias for calling [Builder.permission] with `permission.orElse(null)`. */ + fun permission(permission: Optional) = permission(permission.getOrNull()) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * Sets [Builder.permission] to an arbitrary JSON value. + * + * You should usually call [Builder.permission] with a well-typed [Permission] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun permission(permission: JsonField) = apply { + this.permission = permission + } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * When setting a permission directly, optionally restricts the permission grant to just + * the specified object type. Cannot be set alongside a `role_id`. + */ + fun restrictObjectType(restrictObjectType: AclObjectType?) = + restrictObjectType(JsonField.ofNullable(restrictObjectType)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Alias for calling [Builder.restrictObjectType] with + * `restrictObjectType.orElse(null)`. + */ + fun restrictObjectType(restrictObjectType: Optional) = + restrictObjectType(restrictObjectType.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.restrictObjectType] to an arbitrary JSON value. + * + * You should usually call [Builder.restrictObjectType] with a well-typed + * [AclObjectType] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun restrictObjectType(restrictObjectType: JsonField) = apply { + this.restrictObjectType = restrictObjectType + } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** + * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be + * provided + */ + fun roleId(roleId: String?) = roleId(JsonField.ofNullable(roleId)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ + fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.roleId] to an arbitrary JSON value. + * + * You should usually call [Builder.roleId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun roleId(roleId: JsonField) = apply { this.roleId = roleId } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + /** + * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be + * provided + */ + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** + * 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 additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } - - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + groupId, + permission, + restrictObjectType, + roleId, + userId, + additionalProperties.toMutableMap(), + ) } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + private var validated: Boolean = false - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + fun validate(): Body = apply { + if (validated) { + return@apply } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + objectId() + objectType().validate() + groupId() + permission().ifPresent { it.validate() } + restrictObjectType().ifPresent { it.validate() } + roleId() + userId() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + /** - * Returns an immutable instance of [AclCreateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .objectId() - * .objectType() - * ``` + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * @throws IllegalStateException if any required field is unset. + * Used for best match union deserialization. */ - fun build(): AclCreateParams = - AclCreateParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + @JvmSynthetic + internal fun validity(): Int = + (if (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (groupId.asKnown().isPresent) 1 else 0) + + (permission.asKnown().getOrNull()?.validity() ?: 0) + + (restrictObjectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (roleId.asKnown().isPresent) 1 else 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 && objectId == other.objectId && objectType == other.objectType && groupId == other.groupId && permission == other.permission && restrictObjectType == other.restrictObjectType && roleId == other.roleId && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objectId, objectType, groupId, permission, restrictObjectType, roleId, userId, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{objectId=$objectId, objectType=$objectType, groupId=$groupId, permission=$permission, restrictObjectType=$restrictObjectType, roleId=$roleId, userId=$userId, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclDeleteParams.kt index 1aaf3f66..9b05873d 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclDeleteParams.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,26 +23,11 @@ private constructor( /** Acl id */ fun aclId(): String = aclId - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> aclId - else -> "" - } - } + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -61,7 +45,6 @@ private constructor( } /** A builder for [AclDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var aclId: String? = null @@ -221,6 +204,19 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> aclId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclFindAndDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclFindAndDeleteParams.kt index 5f778de3..05969c71 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclFindAndDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclFindAndDeleteParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -143,696 +141,749 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun toBuilder() = Builder().from(this) - /** - * An ACL grants a certain permission or role to a certain user or group on an object. - * - * ACLs are inherited across the object hierarchy. So for example, if a user has read - * permissions on a project, they will also have read permissions on any experiment, dataset, - * etc. created within that project. - * - * To restrict a grant to a particular sub-object, you may specify `restrict_object_type` in the - * ACL, as part of a direct permission grant or as part of a role. - */ - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("group_id") - @ExcludeMissing - private val groupId: JsonField = JsonMissing.of(), - @JsonProperty("permission") - @ExcludeMissing - private val permission: JsonField = JsonMissing.of(), - @JsonProperty("restrict_object_type") - @ExcludeMissing - private val restrictObjectType: JsonField = JsonMissing.of(), - @JsonProperty("role_id") - @ExcludeMissing - private val roleId: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + companion object { /** - * The id of the object the ACL applies to + * Returns a mutable builder for constructing an instance of [AclFindAndDeleteParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` */ - fun objectId(): String = objectId.getRequired("object_id") + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AclFindAndDeleteParams]. */ + 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(aclFindAndDeleteParams: AclFindAndDeleteParams) = apply { + body = aclFindAndDeleteParams.body.toBuilder() + additionalHeaders = aclFindAndDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = aclFindAndDeleteParams.additionalQueryParams.toBuilder() + } /** - * The object type that the ACL applies to + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * 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: + * - [objectId] + * - [objectType] + * - [groupId] + * - [permission] + * - [restrictObjectType] + * - etc. */ - fun objectType(): AclObjectType = objectType.getRequired("object_type") + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** The id of the object the ACL applies to */ + fun objectId(objectId: String) = apply { body.objectId(objectId) } /** - * Id of the group the ACL applies to. Exactly one of `user_id` and `group_id` will be - * provided + * Sets [Builder.objectId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.objectId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - fun groupId(): Optional = Optional.ofNullable(groupId.getNullable("group_id")) + fun objectId(objectId: JsonField) = apply { body.objectId(objectId) } + + /** The object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = apply { body.objectType(objectType) } /** - * Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided + * Sets [Builder.objectType] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun permission(): Optional = - Optional.ofNullable(permission.getNullable("permission")) + fun objectType(objectType: JsonField) = apply { body.objectType(objectType) } /** - * When setting a permission directly, optionally restricts the permission grant to just the - * specified object type. Cannot be set alongside a `role_id`. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * Id of the group the ACL applies to. Exactly one of `user_id` and `group_id` will be + * provided */ - fun restrictObjectType(): Optional = - Optional.ofNullable(restrictObjectType.getNullable("restrict_object_type")) + fun groupId(groupId: String?) = apply { body.groupId(groupId) } + + /** Alias for calling [Builder.groupId] with `groupId.orElse(null)`. */ + fun groupId(groupId: Optional) = groupId(groupId.getOrNull()) /** - * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be provided + * Sets [Builder.groupId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.groupId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - fun roleId(): Optional = Optional.ofNullable(roleId.getNullable("role_id")) + fun groupId(groupId: JsonField) = apply { body.groupId(groupId) } + + /** Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided */ + fun permission(permission: Permission?) = apply { body.permission(permission) } + + /** Alias for calling [Builder.permission] with `permission.orElse(null)`. */ + fun permission(permission: Optional) = permission(permission.getOrNull()) /** - * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be - * provided + * Sets [Builder.permission] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.permission] with a well-typed [Permission] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) + fun permission(permission: JsonField) = apply { body.permission(permission) } /** - * Returns the raw JSON value of [objectId]. - * - * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. + * When setting a permission directly, optionally restricts the permission grant to just the + * specified object type. Cannot be set alongside a `role_id`. */ - @JsonProperty("object_id") @ExcludeMissing fun _objectId(): JsonField = objectId + fun restrictObjectType(restrictObjectType: AclObjectType?) = apply { + body.restrictObjectType(restrictObjectType) + } /** - * Returns the raw JSON value of [objectType]. - * - * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + * Alias for calling [Builder.restrictObjectType] with `restrictObjectType.orElse(null)`. */ - @JsonProperty("object_type") - @ExcludeMissing - fun _objectType(): JsonField = objectType + fun restrictObjectType(restrictObjectType: Optional) = + restrictObjectType(restrictObjectType.getOrNull()) /** - * Returns the raw JSON value of [groupId]. + * Sets [Builder.restrictObjectType] to an arbitrary JSON value. * - * Unlike [groupId], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.restrictObjectType] with a well-typed [AclObjectType] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. */ - @JsonProperty("group_id") @ExcludeMissing fun _groupId(): JsonField = groupId + fun restrictObjectType(restrictObjectType: JsonField) = apply { + body.restrictObjectType(restrictObjectType) + } /** - * Returns the raw JSON value of [permission]. - * - * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. + * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be provided */ - @JsonProperty("permission") - @ExcludeMissing - fun _permission(): JsonField = permission + fun roleId(roleId: String?) = apply { body.roleId(roleId) } + + /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ + fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) /** - * Returns the raw JSON value of [restrictObjectType]. + * Sets [Builder.roleId] to an arbitrary JSON value. * - * Unlike [restrictObjectType], this method doesn't throw if the JSON field has an - * unexpected type. + * You should usually call [Builder.roleId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("restrict_object_type") - @ExcludeMissing - fun _restrictObjectType(): JsonField = restrictObjectType + fun roleId(roleId: JsonField) = apply { body.roleId(roleId) } /** - * Returns the raw JSON value of [roleId]. - * - * Unlike [roleId], this method doesn't throw if the JSON field has an unexpected type. + * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be + * provided */ - @JsonProperty("role_id") @ExcludeMissing fun _roleId(): JsonField = roleId + fun userId(userId: String?) = apply { body.userId(userId) } + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) /** - * Returns the raw JSON value of [userId]. + * Sets [Builder.userId] to an arbitrary JSON value. * - * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + fun userId(userId: JsonField) = apply { body.userId(userId) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var validated: Boolean = false + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - fun validate(): Body = apply { - if (validated) { - return@apply + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - objectId() - objectType() - groupId() - permission() - restrictObjectType() - roleId() - userId() - validated = true - } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun toBuilder() = Builder().from(this) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - companion object { + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .objectId() - * .objectType() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - private var objectId: JsonField? = null - private var objectType: JsonField? = null - private var groupId: JsonField = JsonMissing.of() - private var permission: JsonField = JsonMissing.of() - private var restrictObjectType: JsonField = JsonMissing.of() - private var roleId: JsonField = JsonMissing.of() - private var userId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - @JvmSynthetic - internal fun from(body: Body) = apply { - objectId = body.objectId - objectType = body.objectType - groupId = body.groupId - permission = body.permission - restrictObjectType = body.restrictObjectType - roleId = body.roleId - userId = body.userId - additionalProperties = body.additionalProperties.toMutableMap() - } + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** The id of the object the ACL applies to */ - fun objectId(objectId: String) = objectId(JsonField.of(objectId)) - - /** - * Sets [Builder.objectId] to an arbitrary JSON value. - * - * You should usually call [Builder.objectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun objectId(objectId: JsonField) = apply { this.objectId = objectId } - - /** The object type that the ACL applies to */ - fun objectType(objectType: AclObjectType) = objectType(JsonField.of(objectType)) - - /** - * Sets [Builder.objectType] to an arbitrary JSON value. - * - * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun objectType(objectType: JsonField) = apply { - this.objectType = objectType - } - - /** - * Id of the group the ACL applies to. Exactly one of `user_id` and `group_id` will be - * provided - */ - fun groupId(groupId: String?) = groupId(JsonField.ofNullable(groupId)) - - /** Alias for calling [Builder.groupId] with `groupId.orElse(null)`. */ - fun groupId(groupId: Optional) = groupId(groupId.getOrNull()) - - /** - * Sets [Builder.groupId] to an arbitrary JSON value. - * - * You should usually call [Builder.groupId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun groupId(groupId: JsonField) = apply { this.groupId = groupId } - - /** - * Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided - */ - fun permission(permission: Permission?) = permission(JsonField.ofNullable(permission)) - - /** Alias for calling [Builder.permission] with `permission.orElse(null)`. */ - fun permission(permission: Optional) = permission(permission.getOrNull()) - - /** - * Sets [Builder.permission] to an arbitrary JSON value. - * - * You should usually call [Builder.permission] with a well-typed [Permission] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun permission(permission: JsonField) = apply { - this.permission = permission - } - - /** - * When setting a permission directly, optionally restricts the permission grant to just - * the specified object type. Cannot be set alongside a `role_id`. - */ - fun restrictObjectType(restrictObjectType: AclObjectType?) = - restrictObjectType(JsonField.ofNullable(restrictObjectType)) - - /** - * Alias for calling [Builder.restrictObjectType] with - * `restrictObjectType.orElse(null)`. - */ - fun restrictObjectType(restrictObjectType: Optional) = - restrictObjectType(restrictObjectType.getOrNull()) - - /** - * Sets [Builder.restrictObjectType] to an arbitrary JSON value. - * - * You should usually call [Builder.restrictObjectType] with a well-typed - * [AclObjectType] value instead. This method is primarily for setting the field to an - * undocumented or not yet supported value. - */ - fun restrictObjectType(restrictObjectType: JsonField) = apply { - this.restrictObjectType = restrictObjectType - } - - /** - * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be - * provided - */ - fun roleId(roleId: String?) = roleId(JsonField.ofNullable(roleId)) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ - fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * Sets [Builder.roleId] to an arbitrary JSON value. - * - * You should usually call [Builder.roleId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun roleId(roleId: JsonField) = apply { this.roleId = roleId } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** - * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be - * provided - */ - fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ - fun userId(userId: Optional) = userId(userId.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * 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 removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .objectId() - * .objectType() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("objectId", objectId), - checkRequired("objectType", objectType), - groupId, - permission, - restrictObjectType, - roleId, - userId, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && objectId == other.objectId && objectType == other.objectType && groupId == other.groupId && permission == other.permission && restrictObjectType == other.restrictObjectType && roleId == other.roleId && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(objectId, objectType, groupId, permission, restrictObjectType, roleId, userId, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{objectId=$objectId, objectType=$objectType, groupId=$groupId, permission=$permission, restrictObjectType=$restrictObjectType, roleId=$roleId, userId=$userId, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [AclFindAndDeleteParams]. + * Returns an immutable instance of [AclFindAndDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java * .objectId() * .objectType() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): AclFindAndDeleteParams = + AclFindAndDeleteParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [AclFindAndDeleteParams]. */ - @NoAutoDetect - class Builder internal constructor() { + fun _body(): Body = body - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + override fun _headers(): Headers = additionalHeaders - @JvmSynthetic - internal fun from(aclFindAndDeleteParams: AclFindAndDeleteParams) = apply { - body = aclFindAndDeleteParams.body.toBuilder() - additionalHeaders = aclFindAndDeleteParams.additionalHeaders.toBuilder() - additionalQueryParams = aclFindAndDeleteParams.additionalQueryParams.toBuilder() - } + override fun _queryParams(): QueryParams = additionalQueryParams - /** The id of the object the ACL applies to */ - fun objectId(objectId: String) = apply { body.objectId(objectId) } + /** + * An ACL grants a certain permission or role to a certain user or group on an object. + * + * ACLs are inherited across the object hierarchy. So for example, if a user has read + * permissions on a project, they will also have read permissions on any experiment, dataset, + * etc. created within that project. + * + * To restrict a grant to a particular sub-object, you may specify `restrict_object_type` in the + * ACL, as part of a direct permission grant or as part of a role. + */ + class Body + private constructor( + private val objectId: JsonField, + private val objectType: JsonField, + private val groupId: JsonField, + private val permission: JsonField, + private val restrictObjectType: JsonField, + private val roleId: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("object_id") + @ExcludeMissing + objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("group_id") @ExcludeMissing groupId: JsonField = JsonMissing.of(), + @JsonProperty("permission") + @ExcludeMissing + permission: JsonField = JsonMissing.of(), + @JsonProperty("restrict_object_type") + @ExcludeMissing + restrictObjectType: JsonField = JsonMissing.of(), + @JsonProperty("role_id") @ExcludeMissing roleId: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this( + objectId, + objectType, + groupId, + permission, + restrictObjectType, + roleId, + userId, + mutableMapOf(), + ) /** - * Sets [Builder.objectId] to an arbitrary JSON value. + * The id of the object the ACL applies to * - * You should usually call [Builder.objectId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException 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 objectId(objectId: JsonField) = apply { body.objectId(objectId) } - - /** The object type that the ACL applies to */ - fun objectType(objectType: AclObjectType) = apply { body.objectType(objectType) } + fun objectId(): String = objectId.getRequired("object_id") /** - * Sets [Builder.objectType] to an arbitrary JSON value. + * The object type that the ACL applies to * - * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException 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 objectType(objectType: JsonField) = apply { body.objectType(objectType) } + fun objectType(): AclObjectType = objectType.getRequired("object_type") /** * Id of the group the ACL applies to. Exactly one of `user_id` and `group_id` will be * provided + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun groupId(groupId: String?) = apply { body.groupId(groupId) } - - /** Alias for calling [Builder.groupId] with `groupId.orElse(null)`. */ - fun groupId(groupId: Optional) = groupId(groupId.getOrNull()) + fun groupId(): Optional = groupId.getOptional("group_id") /** - * Sets [Builder.groupId] to an arbitrary JSON value. + * Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided * - * You should usually call [Builder.groupId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun groupId(groupId: JsonField) = apply { body.groupId(groupId) } + fun permission(): Optional = permission.getOptional("permission") - /** Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided */ - fun permission(permission: Permission?) = apply { body.permission(permission) } + /** + * When setting a permission directly, optionally restricts the permission grant to just the + * specified object type. Cannot be set alongside a `role_id`. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun restrictObjectType(): Optional = + restrictObjectType.getOptional("restrict_object_type") - /** Alias for calling [Builder.permission] with `permission.orElse(null)`. */ - fun permission(permission: Optional) = permission(permission.getOrNull()) + /** + * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be provided + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun roleId(): Optional = roleId.getOptional("role_id") /** - * Sets [Builder.permission] to an arbitrary JSON value. + * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be + * provided * - * You should usually call [Builder.permission] with a well-typed [Permission] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun permission(permission: JsonField) = apply { body.permission(permission) } + fun userId(): Optional = userId.getOptional("user_id") /** - * When setting a permission directly, optionally restricts the permission grant to just the - * specified object type. Cannot be set alongside a `role_id`. + * Returns the raw JSON value of [objectId]. + * + * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. */ - fun restrictObjectType(restrictObjectType: AclObjectType?) = apply { - body.restrictObjectType(restrictObjectType) - } + @JsonProperty("object_id") @ExcludeMissing fun _objectId(): JsonField = objectId /** - * Alias for calling [Builder.restrictObjectType] with `restrictObjectType.orElse(null)`. + * Returns the raw JSON value of [objectType]. + * + * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. */ - fun restrictObjectType(restrictObjectType: Optional) = - restrictObjectType(restrictObjectType.getOrNull()) + @JsonProperty("object_type") + @ExcludeMissing + fun _objectType(): JsonField = objectType /** - * Sets [Builder.restrictObjectType] to an arbitrary JSON value. + * Returns the raw JSON value of [groupId]. * - * You should usually call [Builder.restrictObjectType] with a well-typed [AclObjectType] - * value instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. + * Unlike [groupId], this method doesn't throw if the JSON field has an unexpected type. */ - fun restrictObjectType(restrictObjectType: JsonField) = apply { - body.restrictObjectType(restrictObjectType) - } + @JsonProperty("group_id") @ExcludeMissing fun _groupId(): JsonField = groupId /** - * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be provided + * Returns the raw JSON value of [permission]. + * + * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. */ - fun roleId(roleId: String?) = apply { body.roleId(roleId) } + @JsonProperty("permission") + @ExcludeMissing + fun _permission(): JsonField = permission - /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ - fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) + /** + * Returns the raw JSON value of [restrictObjectType]. + * + * Unlike [restrictObjectType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("restrict_object_type") + @ExcludeMissing + fun _restrictObjectType(): JsonField = restrictObjectType /** - * Sets [Builder.roleId] to an arbitrary JSON value. + * Returns the raw JSON value of [roleId]. * - * You should usually call [Builder.roleId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [roleId], this method doesn't throw if the JSON field has an unexpected type. */ - fun roleId(roleId: JsonField) = apply { body.roleId(roleId) } + @JsonProperty("role_id") @ExcludeMissing fun _roleId(): JsonField = roleId /** - * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be - * provided + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. */ - fun userId(userId: String?) = apply { body.userId(userId) } + @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 [Body]. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var objectId: JsonField? = null + private var objectType: JsonField? = null + private var groupId: JsonField = JsonMissing.of() + private var permission: JsonField = JsonMissing.of() + private var restrictObjectType: JsonField = JsonMissing.of() + private var roleId: JsonField = JsonMissing.of() + private var userId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + objectId = body.objectId + objectType = body.objectType + groupId = body.groupId + permission = body.permission + restrictObjectType = body.restrictObjectType + roleId = body.roleId + userId = body.userId + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** The id of the object the ACL applies to */ + fun objectId(objectId: String) = objectId(JsonField.of(objectId)) + + /** + * Sets [Builder.objectId] to an arbitrary JSON value. + * + * You should usually call [Builder.objectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectId(objectId: JsonField) = apply { this.objectId = objectId } + + /** The object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = objectType(JsonField.of(objectType)) + + /** + * Sets [Builder.objectType] to an arbitrary JSON value. + * + * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectType(objectType: JsonField) = apply { + this.objectType = objectType + } + + /** + * Id of the group the ACL applies to. Exactly one of `user_id` and `group_id` will be + * provided + */ + fun groupId(groupId: String?) = groupId(JsonField.ofNullable(groupId)) - /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ - fun userId(userId: Optional) = userId(userId.getOrNull()) + /** Alias for calling [Builder.groupId] with `groupId.orElse(null)`. */ + fun groupId(groupId: Optional) = groupId(groupId.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 { body.userId(userId) } + /** + * Sets [Builder.groupId] to an arbitrary JSON value. + * + * You should usually call [Builder.groupId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun groupId(groupId: JsonField) = apply { this.groupId = groupId } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) - } + /** + * Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided + */ + fun permission(permission: Permission?) = permission(JsonField.ofNullable(permission)) - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } + /** Alias for calling [Builder.permission] with `permission.orElse(null)`. */ + fun permission(permission: Optional) = permission(permission.getOrNull()) - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) + /** + * Sets [Builder.permission] to an arbitrary JSON value. + * + * You should usually call [Builder.permission] with a well-typed [Permission] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun permission(permission: JsonField) = apply { + this.permission = permission } - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** + * When setting a permission directly, optionally restricts the permission grant to just + * the specified object type. Cannot be set alongside a `role_id`. + */ + fun restrictObjectType(restrictObjectType: AclObjectType?) = + restrictObjectType(JsonField.ofNullable(restrictObjectType)) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Alias for calling [Builder.restrictObjectType] with + * `restrictObjectType.orElse(null)`. + */ + fun restrictObjectType(restrictObjectType: Optional) = + restrictObjectType(restrictObjectType.getOrNull()) - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Sets [Builder.restrictObjectType] to an arbitrary JSON value. + * + * You should usually call [Builder.restrictObjectType] with a well-typed + * [AclObjectType] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun restrictObjectType(restrictObjectType: JsonField) = apply { + this.restrictObjectType = restrictObjectType + } - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** + * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be + * provided + */ + fun roleId(roleId: String?) = roleId(JsonField.ofNullable(roleId)) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ + fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Sets [Builder.roleId] to an arbitrary JSON value. + * + * You should usually call [Builder.roleId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun roleId(roleId: JsonField) = apply { this.roleId = roleId } - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be + * provided + */ + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** + * 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 replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + groupId, + permission, + restrictObjectType, + roleId, + userId, + additionalProperties.toMutableMap(), + ) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + private var validated: Boolean = false - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun validate(): Body = apply { + if (validated) { + return@apply + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) + objectId() + objectType().validate() + groupId() + permission().ifPresent { it.validate() } + restrictObjectType().ifPresent { it.validate() } + roleId() + userId() + validated = true } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } + /** + * Returns 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 (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (groupId.asKnown().isPresent) 1 else 0) + + (permission.asKnown().getOrNull()?.validity() ?: 0) + + (restrictObjectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (roleId.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + return /* spotless:off */ other is Body && objectId == other.objectId && objectType == other.objectType && groupId == other.groupId && permission == other.permission && restrictObjectType == other.restrictObjectType && roleId == other.roleId && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objectId, objectType, groupId, permission, restrictObjectType, roleId, userId, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [AclFindAndDeleteParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .objectId() - * .objectType() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): AclFindAndDeleteParams = - AclFindAndDeleteParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{objectId=$objectId, objectType=$objectType, groupId=$groupId, permission=$permission, restrictObjectType=$restrictObjectType, roleId=$roleId, userId=$userId, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListPage.kt index 5804bf46..fd5ac29d 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListPage.kt @@ -2,161 +2,114 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.AclService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all acls. The acls are sorted by creation date, with the most recently-created acls - * coming first - */ +/** @see [AclService.list] */ class AclListPage private constructor( - private val aclsService: AclService, + private val service: AclService, private val params: AclListParams, - private val response: Response, + private val response: AclListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [AclListPageResponse], but gracefully handles missing data. + * + * @see [AclListPageResponse.objects] + */ + fun objects(): List = response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AclListPage && aclsService == other.aclsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(aclsService, params, response) /* spotless:on */ - - override fun toString() = - "AclListPage{aclsService=$aclsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - AclListParams.builder().from(params).endingBefore(objects().first().id()).build() - ) - } else { - Optional.of( - AclListParams.builder().from(params).startingAfter(objects().last().id()).build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { aclsService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(aclsService: AclService, params: AclListParams, response: Response) = - AclListPage(aclsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): AclListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): AclListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [AclListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [AclListPage]. */ + class Builder internal constructor() { - companion object { + private var service: AclService? = null + private var params: AclListParams? = null + private var response: AclListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [AclListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(aclListPage: AclListPage) = apply { + service = aclListPage.service + params = aclListPage.params + response = aclListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: AclService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: AclListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: AclListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [AclListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AclListPage = + AclListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: AclListPage) : Iterable { @@ -177,4 +130,16 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is AclListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = "AclListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListPageAsync.kt index acd71877..20160da8 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListPageAsync.kt @@ -2,163 +2,118 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.AclServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all acls. The acls are sorted by creation date, with the most recently-created acls - * coming first - */ +/** @see [AclServiceAsync.list] */ class AclListPageAsync private constructor( - private val aclsService: AclServiceAsync, + private val service: AclServiceAsync, private val params: AclListParams, - private val response: Response, + private val response: AclListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [AclListPageResponse], but gracefully handles missing data. + * + * @see [AclListPageResponse.objects] + */ + fun objects(): List = response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AclListPageAsync && aclsService == other.aclsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(aclsService, params, response) /* spotless:on */ - - override fun toString() = - "AclListPageAsync{aclsService=$aclsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - AclListParams.builder().from(params).endingBefore(objects().first().id()).build() - ) - } else { - Optional.of( - AclListParams.builder().from(params).startingAfter(objects().last().id()).build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { aclsService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(aclsService: AclServiceAsync, params: AclListParams, response: Response) = - AclListPageAsync(aclsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): AclListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): AclListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [AclListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [AclListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: AclServiceAsync? = null + private var params: AclListParams? = null + private var response: AclListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [AclListPageAsync]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(aclListPageAsync: AclListPageAsync) = apply { + service = aclListPageAsync.service + params = aclListPageAsync.params + response = aclListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: AclServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: AclListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: AclListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [AclListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AclListPageAsync = + AclListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: AclListPageAsync) { @@ -186,4 +141,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is AclListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "AclListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListPageResponse.kt new file mode 100644 index 00000000..63b51fd2 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListPageResponse.kt @@ -0,0 +1,192 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class AclListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") @ExcludeMissing objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of acl objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [AclListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AclListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aclListPageResponse: AclListPageResponse) = apply { + objects = aclListPageResponse.objects.map { it.toMutableList() } + additionalProperties = aclListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of acl objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [Acl] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: Acl) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AclListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AclListPageResponse = + AclListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AclListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is AclListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AclListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListParams.kt index a49c07f5..238ae30f 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListParams.kt @@ -2,23 +2,11 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -76,31 +64,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - put("object_id", objectId) - put("object_type", objectType.asString()) - endingBefore?.let { put("ending_before", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - startingAfter?.let { put("starting_after", it) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -118,7 +81,6 @@ private constructor( } /** A builder for [AclListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var objectId: String? = null @@ -325,17 +287,39 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + put("object_id", objectId) + put("object_type", objectType.toString()) + endingBefore?.let { put("ending_before", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + startingAfter?.let { put("starting_after", it) } + putAll(additionalQueryParams) + } + .build() + /** * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -350,15 +334,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -374,7 +355,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -391,51 +371,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclObjectType.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclObjectType.kt index 90f9091e..727accde 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclObjectType.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclObjectType.kt @@ -148,6 +148,32 @@ class AclObjectType @JsonCreator private constructor(private val value: JsonFiel fun asString(): String = _value().asString().orElseThrow { BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): AclObjectType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclRetrieveParams.kt index a591bf37..ab43fccb 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> aclId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [AclRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var aclId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> aclId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretCreateParams.kt index 1fbb51db..6a4e98f4 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretCreateParams.kt @@ -6,18 +6,17 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -113,562 +112,590 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun toBuilder() = Builder().from(this) - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("org_name") - @ExcludeMissing - private val orgName: JsonField = JsonMissing.of(), - @JsonProperty("secret") - @ExcludeMissing - private val secret: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + companion object { /** - * Name of the AI secret + * Returns a mutable builder for constructing an instance of [AiSecretCreateParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .name() + * ``` */ - fun name(): String = name.getRequired("name") + @JvmStatic fun builder() = Builder() + } - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + /** A builder for [AiSecretCreateParams]. */ + 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(aiSecretCreateParams: AiSecretCreateParams) = apply { + body = aiSecretCreateParams.body.toBuilder() + additionalHeaders = aiSecretCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = aiSecretCreateParams.additionalQueryParams.toBuilder() + } /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the AI Secret belongs in. + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [name] + * - [metadata] + * - [orgName] + * - [secret] + * - [type] + * - etc. */ - fun orgName(): Optional = Optional.ofNullable(orgName.getNullable("org_name")) + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the AI secret */ + fun name(name: String) = apply { body.name(name) } /** - * Secret value. If omitted in a PUT request, the existing secret value will be left intact, - * not replaced with null. + * Sets [Builder.name] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected 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 secret(): Optional = Optional.ofNullable(secret.getNullable("secret")) + fun name(name: JsonField) = apply { body.name(name) } - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + fun metadata(metadata: Metadata?) = apply { body.metadata(metadata) } + + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) /** - * Returns the raw JSON value of [name]. + * Sets [Builder.metadata] to an arbitrary JSON value. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun metadata(metadata: JsonField) = apply { body.metadata(metadata) } /** - * Returns the raw JSON value of [metadata]. - * - * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the AI Secret belongs in. */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + fun orgName(orgName: String?) = apply { body.orgName(orgName) } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) /** - * Returns the raw JSON value of [orgName]. + * Sets [Builder.orgName] to an arbitrary JSON value. * - * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.orgName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName + fun orgName(orgName: JsonField) = apply { body.orgName(orgName) } /** - * Returns the raw JSON value of [secret]. - * - * Unlike [secret], this method doesn't throw if the JSON field has an unexpected type. + * Secret value. If omitted in a PUT request, the existing secret value will be left intact, + * not replaced with null. */ - @JsonProperty("secret") @ExcludeMissing fun _secret(): JsonField = secret + fun secret(secret: String?) = apply { body.secret(secret) } + + /** Alias for calling [Builder.secret] with `secret.orElse(null)`. */ + fun secret(secret: Optional) = secret(secret.getOrNull()) /** - * Returns the raw JSON value of [type]. + * Sets [Builder.secret] to an arbitrary JSON value. * - * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.secret] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + fun secret(secret: JsonField) = apply { body.secret(secret) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun type(type: String?) = apply { body.type(type) } - private var validated: Boolean = false + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - fun validate(): Body = apply { - if (validated) { - return@apply - } + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { body.type(type) } - name() - metadata().ifPresent { it.validate() } - orgName() - secret() - type() - validated = true + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) } - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) } - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var name: JsonField? = null - private var metadata: JsonField = JsonMissing.of() - private var orgName: JsonField = JsonMissing.of() - private var secret: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - metadata = body.metadata - orgName = body.orgName - secret = body.secret - type = body.type - additionalProperties = body.additionalProperties.toMutableMap() + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - /** Name of the AI secret */ - 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 removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ - fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * 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 additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the AI Secret belongs in. - */ - fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ - fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** - * Sets [Builder.orgName] to an arbitrary JSON value. - * - * You should usually call [Builder.orgName] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun orgName(orgName: JsonField) = apply { this.orgName = orgName } + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** - * Secret value. If omitted in a PUT request, the existing secret value will be left - * intact, not replaced with null. - */ - fun secret(secret: String?) = secret(JsonField.ofNullable(secret)) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.secret] with `secret.orElse(null)`. */ - fun secret(secret: Optional) = secret(secret.getOrNull()) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * Sets [Builder.secret] to an arbitrary JSON value. - * - * You should usually call [Builder.secret] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun secret(secret: JsonField) = apply { this.secret = secret } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - fun type(type: String?) = type(JsonField.ofNullable(type)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.type] with `type.orElse(null)`. */ - fun type(type: Optional) = type(type.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.type] to an arbitrary JSON value. - * - * You should usually call [Builder.type] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonField) = apply { this.type = type } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("name", name), - metadata, - orgName, - secret, - type, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && name == other.name && metadata == other.metadata && orgName == other.orgName && secret == other.secret && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, metadata, orgName, secret, type, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{name=$name, metadata=$metadata, orgName=$orgName, secret=$secret, type=$type, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [AiSecretCreateParams]. + * Returns an immutable instance of [AiSecretCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java * .name() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): AiSecretCreateParams = + AiSecretCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [AiSecretCreateParams]. */ - @NoAutoDetect - class Builder internal constructor() { + fun _body(): Body = body - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + override fun _headers(): Headers = additionalHeaders - @JvmSynthetic - internal fun from(aiSecretCreateParams: AiSecretCreateParams) = apply { - body = aiSecretCreateParams.body.toBuilder() - additionalHeaders = aiSecretCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = aiSecretCreateParams.additionalQueryParams.toBuilder() - } + override fun _queryParams(): QueryParams = additionalQueryParams - /** Name of the AI secret */ - fun name(name: String) = apply { body.name(name) } + class Body + private constructor( + private val name: JsonField, + private val metadata: JsonField, + private val orgName: JsonField, + private val secret: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), + @JsonProperty("org_name") @ExcludeMissing orgName: JsonField = JsonMissing.of(), + @JsonProperty("secret") @ExcludeMissing secret: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(name, metadata, orgName, secret, type, mutableMapOf()) /** - * Sets [Builder.name] to an arbitrary JSON value. + * Name of the AI secret * - * 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. + * @throws BraintrustInvalidDataException 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(name: JsonField) = apply { body.name(name) } - - fun metadata(metadata: Metadata?) = apply { body.metadata(metadata) } - - /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ - fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) + fun name(): String = name.getRequired("name") /** - * 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. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun metadata(metadata: JsonField) = apply { body.metadata(metadata) } + fun metadata(): Optional = metadata.getOptional("metadata") /** * For nearly all users, this parameter should be unnecessary. But in the rare case that * your API key belongs to multiple organizations, you may specify the name of the * organization the AI Secret belongs in. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun orgName(orgName: String?) = apply { body.orgName(orgName) } - - /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ - fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + fun orgName(): Optional = orgName.getOptional("org_name") /** - * Sets [Builder.orgName] to an arbitrary JSON value. + * Secret value. If omitted in a PUT request, the existing secret value will be left intact, + * not replaced with null. * - * You should usually call [Builder.orgName] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun orgName(orgName: JsonField) = apply { body.orgName(orgName) } + fun secret(): Optional = secret.getOptional("secret") /** - * Secret value. If omitted in a PUT request, the existing secret value will be left intact, - * not replaced with null. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun secret(secret: String?) = apply { body.secret(secret) } + fun type(): Optional = type.getOptional("type") - /** Alias for calling [Builder.secret] with `secret.orElse(null)`. */ - fun secret(secret: Optional) = secret(secret.getOrNull()) + /** + * 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 /** - * Sets [Builder.secret] to an arbitrary JSON value. + * Returns the raw JSON value of [metadata]. * - * You should usually call [Builder.secret] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. */ - fun secret(secret: JsonField) = apply { body.secret(secret) } + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata - fun type(type: String?) = apply { body.type(type) } + /** + * Returns the raw JSON value of [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName - /** Alias for calling [Builder.type] with `type.orElse(null)`. */ - fun type(type: Optional) = type(type.getOrNull()) + /** + * Returns the raw JSON value of [secret]. + * + * Unlike [secret], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("secret") @ExcludeMissing fun _secret(): JsonField = secret /** - * Sets [Builder.type] to an arbitrary JSON value. + * Returns the raw JSON value of [type]. * - * You should usually call [Builder.type] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. */ - fun type(type: JsonField) = apply { body.type(type) } + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(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 + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var metadata: JsonField = JsonMissing.of() + private var orgName: JsonField = JsonMissing.of() + private var secret: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + metadata = body.metadata + orgName = body.orgName + secret = body.secret + type = body.type + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the AI secret */ + fun name(name: String) = name(JsonField.of(name)) - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) - } + /** + * 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 removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * 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 additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the AI Secret belongs in. + */ + fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * Sets [Builder.orgName] to an arbitrary JSON value. + * + * You should usually call [Builder.orgName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun orgName(orgName: JsonField) = apply { this.orgName = orgName } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Secret value. If omitted in a PUT request, the existing secret value will be left + * intact, not replaced with null. + */ + fun secret(secret: String?) = secret(JsonField.ofNullable(secret)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.secret] with `secret.orElse(null)`. */ + fun secret(secret: Optional) = secret(secret.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.secret] to an arbitrary JSON value. + * + * You should usually call [Builder.secret] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun secret(secret: JsonField) = apply { this.secret = secret } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + fun type(type: String?) = type(JsonField.ofNullable(type)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun type(type: JsonField) = apply { this.type = type } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("name", name), + metadata, + orgName, + secret, + type, + additionalProperties.toMutableMap(), + ) } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + private var validated: Boolean = false - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun validate(): Body = apply { + if (validated) { + return@apply } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) + name() + metadata().ifPresent { it.validate() } + orgName() + secret() + type() + validated = true } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (orgName.asKnown().isPresent) 1 else 0) + + (if (secret.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + return /* spotless:off */ other is Body && name == other.name && metadata == other.metadata && orgName == other.orgName && secret == other.secret && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ } - /** - * Returns an immutable instance of [AiSecretCreateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): AiSecretCreateParams = - AiSecretCreateParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, metadata, orgName, secret, type, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, metadata=$metadata, orgName=$orgName, secret=$secret, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Metadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -714,6 +741,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretDeleteParams.kt index 2fa3533f..c0e7a074 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretDeleteParams.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,26 +23,11 @@ private constructor( /** AiSecret id */ fun aiSecretId(): String = aiSecretId - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> aiSecretId - else -> "" - } - } + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -61,7 +45,6 @@ private constructor( } /** A builder for [AiSecretDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var aiSecretId: String? = null @@ -221,6 +204,19 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> aiSecretId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretFindAndDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretFindAndDeleteParams.kt index 40ba1a94..83d28e3b 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretFindAndDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretFindAndDeleteParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -68,187 +66,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("org_name") - @ExcludeMissing - private val orgName: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * Name of the AI secret - * - * @throws BraintrustInvalidDataException 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") - - /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the AI Secret belongs in. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun orgName(): Optional = Optional.ofNullable(orgName.getNullable("org_name")) - - /** - * 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 [orgName]. - * - * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - name() - orgName() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var name: JsonField? = null - private var orgName: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - orgName = body.orgName - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** Name of the AI secret */ - 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 } - - /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the AI Secret belongs in. - */ - fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) - - /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ - fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) - - /** - * Sets [Builder.orgName] to an arbitrary JSON value. - * - * You should usually call [Builder.orgName] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun orgName(orgName: JsonField) = apply { this.orgName = orgName } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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 - * .name() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body(checkRequired("name", name), orgName, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && name == other.name && orgName == other.orgName && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, orgName, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{name=$name, orgName=$orgName, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -265,7 +82,6 @@ private constructor( } /** A builder for [AiSecretFindAndDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -279,6 +95,16 @@ private constructor( additionalQueryParams = aiSecretFindAndDeleteParams.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: + * - [name] + * - [orgName] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** Name of the AI secret */ fun name(name: String) = apply { body.name(name) } @@ -445,6 +271,210 @@ private constructor( ) } + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val name: JsonField, + private val orgName: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("org_name") @ExcludeMissing orgName: JsonField = JsonMissing.of(), + ) : this(name, orgName, mutableMapOf()) + + /** + * Name of the AI secret + * + * @throws BraintrustInvalidDataException 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") + + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the AI Secret belongs in. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun orgName(): Optional = orgName.getOptional("org_name") + + /** + * 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 [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName + + @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 + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var orgName: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + orgName = body.orgName + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the AI secret */ + 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 } + + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the AI Secret belongs in. + */ + fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** + * Sets [Builder.orgName] to an arbitrary JSON value. + * + * You should usually call [Builder.orgName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun orgName(orgName: JsonField) = apply { this.orgName = orgName } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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 + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body(checkRequired("name", name), orgName, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + orgName() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + (if (orgName.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && name == other.name && orgName == other.orgName && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, orgName, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, orgName=$orgName, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListPage.kt index af920955..021f2341 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListPage.kt @@ -2,167 +2,115 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.AiSecretService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all ai_secrets. The ai_secrets are sorted by creation date, with the most - * recently-created ai_secrets coming first - */ +/** @see [AiSecretService.list] */ class AiSecretListPage private constructor( - private val aiSecretsService: AiSecretService, + private val service: AiSecretService, private val params: AiSecretListParams, - private val response: Response, + private val response: AiSecretListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [AiSecretListPageResponse], but gracefully handles missing data. + * + * @see [AiSecretListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AiSecretListPage && aiSecretsService == other.aiSecretsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(aiSecretsService, params, response) /* spotless:on */ - - override fun toString() = - "AiSecretListPage{aiSecretsService=$aiSecretsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - AiSecretListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - AiSecretListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { aiSecretsService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(aiSecretsService: AiSecretService, params: AiSecretListParams, response: Response) = - AiSecretListPage(aiSecretsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): AiSecretListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): AiSecretListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [AiSecretListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [AiSecretListPage]. */ + class Builder internal constructor() { - companion object { + private var service: AiSecretService? = null + private var params: AiSecretListParams? = null + private var response: AiSecretListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [AiSecretListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(aiSecretListPage: AiSecretListPage) = apply { + service = aiSecretListPage.service + params = aiSecretListPage.params + response = aiSecretListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: AiSecretService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: AiSecretListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: AiSecretListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [AiSecretListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AiSecretListPage = + AiSecretListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: AiSecretListPage) : Iterable { @@ -183,4 +131,17 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is AiSecretListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "AiSecretListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListPageAsync.kt index 441b79ce..597dd9cd 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListPageAsync.kt @@ -2,174 +2,119 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.AiSecretServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all ai_secrets. The ai_secrets are sorted by creation date, with the most - * recently-created ai_secrets coming first - */ +/** @see [AiSecretServiceAsync.list] */ class AiSecretListPageAsync private constructor( - private val aiSecretsService: AiSecretServiceAsync, + private val service: AiSecretServiceAsync, private val params: AiSecretListParams, - private val response: Response, + private val response: AiSecretListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [AiSecretListPageResponse], but gracefully handles missing data. + * + * @see [AiSecretListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AiSecretListPageAsync && aiSecretsService == other.aiSecretsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(aiSecretsService, params, response) /* spotless:on */ - - override fun toString() = - "AiSecretListPageAsync{aiSecretsService=$aiSecretsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - AiSecretListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - AiSecretListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { aiSecretsService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of( - aiSecretsService: AiSecretServiceAsync, - params: AiSecretListParams, - response: Response, - ) = AiSecretListPageAsync(aiSecretsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): AiSecretListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): AiSecretListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [AiSecretListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [AiSecretListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: AiSecretServiceAsync? = null + private var params: AiSecretListParams? = null + private var response: AiSecretListPageResponse? = null - /** - * Returns a mutable builder for constructing an instance of [AiSecretListPageAsync]. - */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(aiSecretListPageAsync: AiSecretListPageAsync) = apply { + service = aiSecretListPageAsync.service + params = aiSecretListPageAsync.params + response = aiSecretListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: AiSecretServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: AiSecretListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: AiSecretListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [AiSecretListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AiSecretListPageAsync = + AiSecretListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: AiSecretListPageAsync) { @@ -197,4 +142,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is AiSecretListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "AiSecretListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListPageResponse.kt new file mode 100644 index 00000000..57a8dde7 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListPageResponse.kt @@ -0,0 +1,194 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class AiSecretListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") + @ExcludeMissing + objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of ai_secret objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [AiSecretListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AiSecretListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aiSecretListPageResponse: AiSecretListPageResponse) = apply { + objects = aiSecretListPageResponse.objects.map { it.toMutableList() } + additionalProperties = aiSecretListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of ai_secret objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [AISecret] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: AISecret) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AiSecretListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AiSecretListPageResponse = + AiSecretListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AiSecretListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is AiSecretListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AiSecretListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListParams.kt index 4359719a..dd7ef4bd 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListParams.kt @@ -2,22 +2,10 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -78,42 +66,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - aiSecretName?.let { put("ai_secret_name", it) } - aiSecretType?.accept( - object : AiSecretType.Visitor { - override fun visitString(string: String) { - put("ai_secret_type", string) - } - - override fun visitStrings(strings: List) { - put("ai_secret_type", strings.joinToString(",")) - } - } - ) - endingBefore?.let { put("ending_before", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - orgName?.let { put("org_name", it) } - startingAfter?.let { put("starting_after", it) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -125,7 +77,6 @@ private constructor( } /** A builder for [AiSecretListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var aiSecretName: String? = null @@ -346,13 +297,46 @@ private constructor( ) } - @JsonDeserialize(using = AiSecretType.Deserializer::class) - @JsonSerialize(using = AiSecretType.Serializer::class) + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + aiSecretName?.let { put("ai_secret_name", it) } + aiSecretType?.accept( + object : AiSecretType.Visitor { + override fun visitString(string: String) { + put("ai_secret_type", string) + } + + override fun visitStrings(strings: List) { + put("ai_secret_type", strings.joinToString(",")) + } + } + ) + endingBefore?.let { put("ending_before", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + orgName?.let { put("org_name", it) } + startingAfter?.let { put("starting_after", it) } + putAll(additionalQueryParams) + } + .build() + class AiSecretType private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -367,15 +351,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid AiSecretType") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -391,7 +372,6 @@ private constructor( when { string != null -> "AiSecretType{string=$string}" strings != null -> "AiSecretType{strings=$strings}" - _json != null -> "AiSecretType{_unknown=$_json}" else -> throw IllegalStateException("Invalid AiSecretType") } @@ -411,52 +391,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [AiSecretType] to a value of type [T]. - * - * An instance of [AiSecretType] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown AiSecretType: $json") - } - } - - internal class Deserializer : BaseDeserializer(AiSecretType::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): AiSecretType { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return AiSecretType(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return AiSecretType(strings = it, _json = json) - } - - return AiSecretType(_json = json) - } - } - - internal class Serializer : BaseSerializer(AiSecretType::class) { - - override fun serialize( - value: AiSecretType, - 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 AiSecretType") - } - } } } @@ -464,13 +398,10 @@ private constructor( * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -485,15 +416,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -509,7 +437,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -526,51 +453,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretReplaceParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretReplaceParams.kt index 9a5a51dd..af588655 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretReplaceParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretReplaceParams.kt @@ -6,18 +6,17 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -113,562 +112,590 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun toBuilder() = Builder().from(this) - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("org_name") - @ExcludeMissing - private val orgName: JsonField = JsonMissing.of(), - @JsonProperty("secret") - @ExcludeMissing - private val secret: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + companion object { /** - * Name of the AI secret + * Returns a mutable builder for constructing an instance of [AiSecretReplaceParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .name() + * ``` */ - fun name(): String = name.getRequired("name") + @JvmStatic fun builder() = Builder() + } - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + /** A builder for [AiSecretReplaceParams]. */ + 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(aiSecretReplaceParams: AiSecretReplaceParams) = apply { + body = aiSecretReplaceParams.body.toBuilder() + additionalHeaders = aiSecretReplaceParams.additionalHeaders.toBuilder() + additionalQueryParams = aiSecretReplaceParams.additionalQueryParams.toBuilder() + } /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the AI Secret belongs in. + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [name] + * - [metadata] + * - [orgName] + * - [secret] + * - [type] + * - etc. */ - fun orgName(): Optional = Optional.ofNullable(orgName.getNullable("org_name")) + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the AI secret */ + fun name(name: String) = apply { body.name(name) } /** - * Secret value. If omitted in a PUT request, the existing secret value will be left intact, - * not replaced with null. + * Sets [Builder.name] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected 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 secret(): Optional = Optional.ofNullable(secret.getNullable("secret")) + fun name(name: JsonField) = apply { body.name(name) } - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + fun metadata(metadata: Metadata?) = apply { body.metadata(metadata) } + + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) /** - * Returns the raw JSON value of [name]. + * Sets [Builder.metadata] to an arbitrary JSON value. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun metadata(metadata: JsonField) = apply { body.metadata(metadata) } /** - * Returns the raw JSON value of [metadata]. - * - * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the AI Secret belongs in. */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + fun orgName(orgName: String?) = apply { body.orgName(orgName) } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) /** - * Returns the raw JSON value of [orgName]. + * Sets [Builder.orgName] to an arbitrary JSON value. * - * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.orgName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName + fun orgName(orgName: JsonField) = apply { body.orgName(orgName) } /** - * Returns the raw JSON value of [secret]. - * - * Unlike [secret], this method doesn't throw if the JSON field has an unexpected type. + * Secret value. If omitted in a PUT request, the existing secret value will be left intact, + * not replaced with null. */ - @JsonProperty("secret") @ExcludeMissing fun _secret(): JsonField = secret + fun secret(secret: String?) = apply { body.secret(secret) } + + /** Alias for calling [Builder.secret] with `secret.orElse(null)`. */ + fun secret(secret: Optional) = secret(secret.getOrNull()) /** - * Returns the raw JSON value of [type]. + * Sets [Builder.secret] to an arbitrary JSON value. * - * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.secret] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + fun secret(secret: JsonField) = apply { body.secret(secret) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun type(type: String?) = apply { body.type(type) } - private var validated: Boolean = false + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - fun validate(): Body = apply { - if (validated) { - return@apply - } + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { body.type(type) } - name() - metadata().ifPresent { it.validate() } - orgName() - secret() - type() - validated = true + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) } - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) } - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var name: JsonField? = null - private var metadata: JsonField = JsonMissing.of() - private var orgName: JsonField = JsonMissing.of() - private var secret: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - metadata = body.metadata - orgName = body.orgName - secret = body.secret - type = body.type - additionalProperties = body.additionalProperties.toMutableMap() + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - /** Name of the AI secret */ - 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 removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ - fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * 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 additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the AI Secret belongs in. - */ - fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ - fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** - * Sets [Builder.orgName] to an arbitrary JSON value. - * - * You should usually call [Builder.orgName] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun orgName(orgName: JsonField) = apply { this.orgName = orgName } + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** - * Secret value. If omitted in a PUT request, the existing secret value will be left - * intact, not replaced with null. - */ - fun secret(secret: String?) = secret(JsonField.ofNullable(secret)) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.secret] with `secret.orElse(null)`. */ - fun secret(secret: Optional) = secret(secret.getOrNull()) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * Sets [Builder.secret] to an arbitrary JSON value. - * - * You should usually call [Builder.secret] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun secret(secret: JsonField) = apply { this.secret = secret } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - fun type(type: String?) = type(JsonField.ofNullable(type)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.type] with `type.orElse(null)`. */ - fun type(type: Optional) = type(type.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.type] to an arbitrary JSON value. - * - * You should usually call [Builder.type] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonField) = apply { this.type = type } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("name", name), - metadata, - orgName, - secret, - type, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && name == other.name && metadata == other.metadata && orgName == other.orgName && secret == other.secret && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, metadata, orgName, secret, type, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{name=$name, metadata=$metadata, orgName=$orgName, secret=$secret, type=$type, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [AiSecretReplaceParams]. + * Returns an immutable instance of [AiSecretReplaceParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java * .name() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): AiSecretReplaceParams = + AiSecretReplaceParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [AiSecretReplaceParams]. */ - @NoAutoDetect - class Builder internal constructor() { + fun _body(): Body = body - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + override fun _headers(): Headers = additionalHeaders - @JvmSynthetic - internal fun from(aiSecretReplaceParams: AiSecretReplaceParams) = apply { - body = aiSecretReplaceParams.body.toBuilder() - additionalHeaders = aiSecretReplaceParams.additionalHeaders.toBuilder() - additionalQueryParams = aiSecretReplaceParams.additionalQueryParams.toBuilder() - } + override fun _queryParams(): QueryParams = additionalQueryParams - /** Name of the AI secret */ - fun name(name: String) = apply { body.name(name) } + class Body + private constructor( + private val name: JsonField, + private val metadata: JsonField, + private val orgName: JsonField, + private val secret: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), + @JsonProperty("org_name") @ExcludeMissing orgName: JsonField = JsonMissing.of(), + @JsonProperty("secret") @ExcludeMissing secret: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(name, metadata, orgName, secret, type, mutableMapOf()) /** - * Sets [Builder.name] to an arbitrary JSON value. + * Name of the AI secret * - * 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. + * @throws BraintrustInvalidDataException 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(name: JsonField) = apply { body.name(name) } - - fun metadata(metadata: Metadata?) = apply { body.metadata(metadata) } - - /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ - fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) + fun name(): String = name.getRequired("name") /** - * 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. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun metadata(metadata: JsonField) = apply { body.metadata(metadata) } + fun metadata(): Optional = metadata.getOptional("metadata") /** * For nearly all users, this parameter should be unnecessary. But in the rare case that * your API key belongs to multiple organizations, you may specify the name of the * organization the AI Secret belongs in. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun orgName(orgName: String?) = apply { body.orgName(orgName) } - - /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ - fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + fun orgName(): Optional = orgName.getOptional("org_name") /** - * Sets [Builder.orgName] to an arbitrary JSON value. + * Secret value. If omitted in a PUT request, the existing secret value will be left intact, + * not replaced with null. * - * You should usually call [Builder.orgName] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun orgName(orgName: JsonField) = apply { body.orgName(orgName) } + fun secret(): Optional = secret.getOptional("secret") /** - * Secret value. If omitted in a PUT request, the existing secret value will be left intact, - * not replaced with null. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun secret(secret: String?) = apply { body.secret(secret) } + fun type(): Optional = type.getOptional("type") - /** Alias for calling [Builder.secret] with `secret.orElse(null)`. */ - fun secret(secret: Optional) = secret(secret.getOrNull()) + /** + * 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 /** - * Sets [Builder.secret] to an arbitrary JSON value. + * Returns the raw JSON value of [metadata]. * - * You should usually call [Builder.secret] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. */ - fun secret(secret: JsonField) = apply { body.secret(secret) } + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata - fun type(type: String?) = apply { body.type(type) } + /** + * Returns the raw JSON value of [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName - /** Alias for calling [Builder.type] with `type.orElse(null)`. */ - fun type(type: Optional) = type(type.getOrNull()) + /** + * Returns the raw JSON value of [secret]. + * + * Unlike [secret], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("secret") @ExcludeMissing fun _secret(): JsonField = secret /** - * Sets [Builder.type] to an arbitrary JSON value. + * Returns the raw JSON value of [type]. * - * You should usually call [Builder.type] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. */ - fun type(type: JsonField) = apply { body.type(type) } + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(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 + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var metadata: JsonField = JsonMissing.of() + private var orgName: JsonField = JsonMissing.of() + private var secret: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + metadata = body.metadata + orgName = body.orgName + secret = body.secret + type = body.type + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the AI secret */ + fun name(name: String) = name(JsonField.of(name)) - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) - } + /** + * 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 removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * 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 additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the AI Secret belongs in. + */ + fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * Sets [Builder.orgName] to an arbitrary JSON value. + * + * You should usually call [Builder.orgName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun orgName(orgName: JsonField) = apply { this.orgName = orgName } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Secret value. If omitted in a PUT request, the existing secret value will be left + * intact, not replaced with null. + */ + fun secret(secret: String?) = secret(JsonField.ofNullable(secret)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.secret] with `secret.orElse(null)`. */ + fun secret(secret: Optional) = secret(secret.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.secret] to an arbitrary JSON value. + * + * You should usually call [Builder.secret] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun secret(secret: JsonField) = apply { this.secret = secret } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + fun type(type: String?) = type(JsonField.ofNullable(type)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun type(type: JsonField) = apply { this.type = type } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("name", name), + metadata, + orgName, + secret, + type, + additionalProperties.toMutableMap(), + ) } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + private var validated: Boolean = false - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun validate(): Body = apply { + if (validated) { + return@apply } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) + name() + metadata().ifPresent { it.validate() } + orgName() + secret() + type() + validated = true } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (orgName.asKnown().isPresent) 1 else 0) + + (if (secret.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + return /* spotless:off */ other is Body && name == other.name && metadata == other.metadata && orgName == other.orgName && secret == other.secret && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ } - /** - * Returns an immutable instance of [AiSecretReplaceParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): AiSecretReplaceParams = - AiSecretReplaceParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, metadata, orgName, secret, type, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, metadata=$metadata, orgName=$orgName, secret=$secret, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Metadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -714,6 +741,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretRetrieveParams.kt index 7ff996d2..551f4d43 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> aiSecretId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [AiSecretRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var aiSecretId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> aiSecretId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretUpdateParams.kt index 751a2ce2..4db720cf 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretUpdateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretUpdateParams.kt @@ -6,18 +6,17 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -98,240 +97,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> aiSecretId - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("secret") - @ExcludeMissing - private val secret: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) - - /** - * Name of the AI secret - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun secret(): Optional = Optional.ofNullable(secret.getNullable("secret")) - - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - /** - * 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 [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 [secret]. - * - * Unlike [secret], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("secret") @ExcludeMissing fun _secret(): JsonField = secret - - /** - * Returns the raw JSON value of [type]. - * - * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - name() - secret() - type() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Body]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var metadata: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var secret: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - metadata = body.metadata - name = body.name - secret = body.secret - type = body.type - additionalProperties = body.additionalProperties.toMutableMap() - } - - 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 } - - /** Name of the AI secret */ - 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 secret(secret: String?) = secret(JsonField.ofNullable(secret)) - - /** Alias for calling [Builder.secret] with `secret.orElse(null)`. */ - fun secret(secret: Optional) = secret(secret.getOrNull()) - - /** - * Sets [Builder.secret] to an arbitrary JSON value. - * - * You should usually call [Builder.secret] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun secret(secret: JsonField) = apply { this.secret = secret } - - fun type(type: String?) = type(JsonField.ofNullable(type)) - - /** Alias for calling [Builder.type] with `type.orElse(null)`. */ - fun type(type: Optional) = type(type.getOrNull()) - - /** - * Sets [Builder.type] to an arbitrary JSON value. - * - * You should usually call [Builder.type] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonField) = apply { this.type = type } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Body = - Body(metadata, name, secret, type, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && metadata == other.metadata && name == other.name && secret == other.secret && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(metadata, name, secret, type, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{metadata=$metadata, name=$name, secret=$secret, type=$type, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -348,7 +113,6 @@ private constructor( } /** A builder for [AiSecretUpdateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var aiSecretId: String? = null @@ -367,6 +131,18 @@ private constructor( /** AiSecret id */ fun aiSecretId(aiSecretId: String) = apply { this.aiSecretId = aiSecretId } + /** + * 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: + * - [metadata] + * - [name] + * - [secret] + * - [type] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + fun metadata(metadata: Metadata?) = apply { body.metadata(metadata) } /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ @@ -559,28 +335,276 @@ private constructor( ) } - @NoAutoDetect - class Metadata - @JsonCreator + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> aiSecretId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + private val metadata: JsonField, + private val name: JsonField, + private val secret: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("secret") @ExcludeMissing secret: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(metadata, name, secret, type, mutableMapOf()) + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * Name of the AI secret + * + * @throws BraintrustInvalidDataException 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 BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun secret(): Optional = secret.getOptional("secret") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [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 [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 [secret]. + * + * Unlike [secret], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("secret") @ExcludeMissing fun _secret(): JsonField = secret + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var metadata: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var secret: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + metadata = body.metadata + name = body.name + secret = body.secret + type = body.type + additionalProperties = body.additionalProperties.toMutableMap() + } + + 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 } + + /** Name of the AI secret */ + 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 secret(secret: String?) = secret(JsonField.ofNullable(secret)) + + /** Alias for calling [Builder.secret] with `secret.orElse(null)`. */ + fun secret(secret: Optional) = secret(secret.getOrNull()) + + /** + * Sets [Builder.secret] to an arbitrary JSON value. + * + * You should usually call [Builder.secret] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun secret(secret: JsonField) = apply { this.secret = secret } + + fun type(type: String?) = type(JsonField.ofNullable(type)) + + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body(metadata, name, secret, type, additionalProperties.toMutableMap()) + } private var validated: Boolean = false - fun validate(): Metadata = apply { + fun validate(): Body = apply { if (validated) { return@apply } + metadata().ifPresent { it.validate() } + name() + secret() + type() validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (secret.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && metadata == other.metadata && name == other.name && secret == other.secret && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(metadata, name, secret, type, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{metadata=$metadata, name=$name, secret=$secret, type=$type, 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 { @@ -626,6 +650,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKey.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKey.kt index 6cebb35a..17e11b99 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKey.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKey.kt @@ -6,39 +6,43 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class ApiKey -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("preview_name") - @ExcludeMissing - private val previewName: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("org_id") @ExcludeMissing private val orgId: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val name: JsonField, + private val previewName: JsonField, + private val created: JsonField, + private val orgId: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("preview_name") + @ExcludeMissing + previewName: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("org_id") @ExcludeMissing orgId: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this(id, name, previewName, created, orgId, userId, mutableMapOf()) + /** * Unique identifier for the api key * @@ -67,7 +71,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Unique identifier for the organization @@ -75,7 +79,7 @@ private constructor( * @throws BraintrustInvalidDataException 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 orgId(): Optional = orgId.getOptional("org_id") /** * Unique identifier for the user @@ -83,7 +87,7 @@ private constructor( * @throws BraintrustInvalidDataException 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 [id]. @@ -129,25 +133,15 @@ private constructor( */ @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 = additionalProperties - - private var validated: Boolean = false - - fun validate(): ApiKey = apply { - if (validated) { - return@apply - } - - id() - name() - previewName() - created() - orgId() - userId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -305,10 +299,48 @@ private constructor( created, orgId, userId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): ApiKey = apply { + if (validated) { + return@apply + } + + id() + name() + previewName() + created() + orgId() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (previewName.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (orgId.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyCreateParams.kt index f00eaec8..236d29be 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyCreateParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -71,187 +69,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("org_name") - @ExcludeMissing - private val orgName: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * Name of the api key. Does not have to be unique - * - * @throws BraintrustInvalidDataException 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") - - /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the API key belongs in. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun orgName(): Optional = Optional.ofNullable(orgName.getNullable("org_name")) - - /** - * 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 [orgName]. - * - * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - name() - orgName() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var name: JsonField? = null - private var orgName: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - orgName = body.orgName - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** Name of the api key. Does not have to be unique */ - 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 } - - /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the API key belongs in. - */ - fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) - - /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ - fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) - - /** - * Sets [Builder.orgName] to an arbitrary JSON value. - * - * You should usually call [Builder.orgName] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun orgName(orgName: JsonField) = apply { this.orgName = orgName } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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 - * .name() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body(checkRequired("name", name), orgName, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && name == other.name && orgName == other.orgName && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, orgName, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{name=$name, orgName=$orgName, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -268,7 +85,6 @@ private constructor( } /** A builder for [ApiKeyCreateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -282,6 +98,16 @@ private constructor( additionalQueryParams = apiKeyCreateParams.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: + * - [name] + * - [orgName] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** Name of the api key. Does not have to be unique */ fun name(name: String) = apply { body.name(name) } @@ -448,6 +274,210 @@ private constructor( ) } + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val name: JsonField, + private val orgName: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("org_name") @ExcludeMissing orgName: JsonField = JsonMissing.of(), + ) : this(name, orgName, mutableMapOf()) + + /** + * Name of the api key. Does not have to be unique + * + * @throws BraintrustInvalidDataException 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") + + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the API key belongs in. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun orgName(): Optional = orgName.getOptional("org_name") + + /** + * 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 [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName + + @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 + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var orgName: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + orgName = body.orgName + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the api key. Does not have to be unique */ + 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 } + + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the API key belongs in. + */ + fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** + * Sets [Builder.orgName] to an arbitrary JSON value. + * + * You should usually call [Builder.orgName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun orgName(orgName: JsonField) = apply { this.orgName = orgName } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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 + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body(checkRequired("name", name), orgName, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + orgName() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + (if (orgName.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && name == other.name && orgName == other.orgName && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, orgName, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, orgName=$orgName, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyDeleteParams.kt index cc0903b2..908060c2 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyDeleteParams.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,26 +23,11 @@ private constructor( /** ApiKey id */ fun apiKeyId(): String = apiKeyId - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> apiKeyId - else -> "" - } - } + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -61,7 +45,6 @@ private constructor( } /** A builder for [ApiKeyDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var apiKeyId: String? = null @@ -221,6 +204,19 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> apiKeyId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListPage.kt index 4d1e410a..0aeea56f 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListPage.kt @@ -2,161 +2,115 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.ApiKeyService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all api_keys. The api_keys are sorted by creation date, with the most recently-created - * api_keys coming first - */ +/** @see [ApiKeyService.list] */ class ApiKeyListPage private constructor( - private val apiKeysService: ApiKeyService, + private val service: ApiKeyService, private val params: ApiKeyListParams, - private val response: Response, + private val response: ApiKeyListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [ApiKeyListPageResponse], but gracefully handles missing data. + * + * @see [ApiKeyListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ApiKeyListPage && apiKeysService == other.apiKeysService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(apiKeysService, params, response) /* spotless:on */ - - override fun toString() = - "ApiKeyListPage{apiKeysService=$apiKeysService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - ApiKeyListParams.builder().from(params).endingBefore(objects().first().id()).build() - ) - } else { - Optional.of( - ApiKeyListParams.builder().from(params).startingAfter(objects().last().id()).build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { apiKeysService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(apiKeysService: ApiKeyService, params: ApiKeyListParams, response: Response) = - ApiKeyListPage(apiKeysService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): ApiKeyListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): ApiKeyListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [ApiKeyListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [ApiKeyListPage]. */ + class Builder internal constructor() { - companion object { + private var service: ApiKeyService? = null + private var params: ApiKeyListParams? = null + private var response: ApiKeyListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [ApiKeyListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(apiKeyListPage: ApiKeyListPage) = apply { + service = apiKeyListPage.service + params = apiKeyListPage.params + response = apiKeyListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: ApiKeyService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: ApiKeyListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ApiKeyListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ApiKeyListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ApiKeyListPage = + ApiKeyListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: ApiKeyListPage) : Iterable { @@ -177,4 +131,16 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ApiKeyListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = "ApiKeyListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListPageAsync.kt index 28dc1058..5bc2cbe9 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListPageAsync.kt @@ -2,163 +2,119 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.ApiKeyServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all api_keys. The api_keys are sorted by creation date, with the most recently-created - * api_keys coming first - */ +/** @see [ApiKeyServiceAsync.list] */ class ApiKeyListPageAsync private constructor( - private val apiKeysService: ApiKeyServiceAsync, + private val service: ApiKeyServiceAsync, private val params: ApiKeyListParams, - private val response: Response, + private val response: ApiKeyListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [ApiKeyListPageResponse], but gracefully handles missing data. + * + * @see [ApiKeyListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ApiKeyListPageAsync && apiKeysService == other.apiKeysService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(apiKeysService, params, response) /* spotless:on */ - - override fun toString() = - "ApiKeyListPageAsync{apiKeysService=$apiKeysService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - ApiKeyListParams.builder().from(params).endingBefore(objects().first().id()).build() - ) - } else { - Optional.of( - ApiKeyListParams.builder().from(params).startingAfter(objects().last().id()).build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { apiKeysService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(apiKeysService: ApiKeyServiceAsync, params: ApiKeyListParams, response: Response) = - ApiKeyListPageAsync(apiKeysService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): ApiKeyListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): ApiKeyListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [ApiKeyListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [ApiKeyListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: ApiKeyServiceAsync? = null + private var params: ApiKeyListParams? = null + private var response: ApiKeyListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [ApiKeyListPageAsync]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(apiKeyListPageAsync: ApiKeyListPageAsync) = apply { + service = apiKeyListPageAsync.service + params = apiKeyListPageAsync.params + response = apiKeyListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: ApiKeyServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: ApiKeyListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ApiKeyListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ApiKeyListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ApiKeyListPageAsync = + ApiKeyListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: ApiKeyListPageAsync) { @@ -186,4 +142,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ApiKeyListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "ApiKeyListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListPageResponse.kt new file mode 100644 index 00000000..9c42308a --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListPageResponse.kt @@ -0,0 +1,192 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class ApiKeyListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") @ExcludeMissing objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of api_key objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [ApiKeyListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ApiKeyListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(apiKeyListPageResponse: ApiKeyListPageResponse) = apply { + objects = apiKeyListPageResponse.objects.map { it.toMutableList() } + additionalProperties = apiKeyListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of api_key objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [ApiKey] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: ApiKey) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ApiKeyListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ApiKeyListPageResponse = + ApiKeyListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ApiKeyListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ApiKeyListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ApiKeyListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListParams.kt index 03c6a458..a1fcb296 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListParams.kt @@ -2,22 +2,10 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -75,31 +63,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - apiKeyName?.let { put("api_key_name", it) } - endingBefore?.let { put("ending_before", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - orgName?.let { put("org_name", it) } - startingAfter?.let { put("starting_after", it) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -111,7 +74,6 @@ private constructor( } /** A builder for [ApiKeyListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var apiKeyName: String? = null @@ -316,17 +278,39 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + apiKeyName?.let { put("api_key_name", it) } + endingBefore?.let { put("ending_before", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + orgName?.let { put("org_name", it) } + startingAfter?.let { put("starting_after", it) } + putAll(additionalQueryParams) + } + .build() + /** * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -341,15 +325,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -365,7 +346,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -382,51 +362,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyRetrieveParams.kt index 1a0b9c18..de3cb891 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> apiKeyId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [ApiKeyRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var apiKeyId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> apiKeyId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartImage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartImage.kt index 5a3d774a..d7fb8bd9 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartImage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartImage.kt @@ -7,29 +7,30 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 -@NoAutoDetect class ChatCompletionContentPartImage -@JsonCreator private constructor( - @JsonProperty("image_url") - @ExcludeMissing - private val imageUrl: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val imageUrl: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("image_url") @ExcludeMissing imageUrl: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(imageUrl, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected value). @@ -56,21 +57,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ChatCompletionContentPartImage = apply { - if (validated) { - return@apply - } - - imageUrl().validate() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -161,22 +156,53 @@ private constructor( ChatCompletionContentPartImage( checkRequired("imageUrl", imageUrl), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): ChatCompletionContentPartImage = apply { + if (validated) { + return@apply + } + + imageUrl().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + class ImageUrl - @JsonCreator private constructor( - @JsonProperty("url") @ExcludeMissing private val url: JsonField = JsonMissing.of(), - @JsonProperty("detail") - @ExcludeMissing - private val detail: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + 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 BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected value). @@ -187,7 +213,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun detail(): Optional = Optional.ofNullable(detail.getNullable("detail")) + fun detail(): Optional = detail.getOptional("detail") /** * Returns the raw JSON value of [url]. @@ -203,21 +229,15 @@ private constructor( */ @JsonProperty("detail") @ExcludeMissing fun _detail(): JsonField = detail + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ImageUrl = apply { - if (validated) { - return@apply - } - - url() - detail() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -302,9 +322,40 @@ private constructor( * @throws IllegalStateException if any required field is unset. */ fun build(): ImageUrl = - ImageUrl(checkRequired("url", url), detail, additionalProperties.toImmutable()) + ImageUrl(checkRequired("url", url), detail, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): ImageUrl = apply { + if (validated) { + return@apply + } + + url() + detail().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + + (detail.asKnown().getOrNull()?.validity() ?: 0) + class Detail @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -400,6 +451,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Detail = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -512,6 +590,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartText.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartText.kt index 4d14c0cf..7452ab93 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartText.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartText.kt @@ -7,27 +7,30 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 -@NoAutoDetect class ChatCompletionContentPartText -@JsonCreator private constructor( - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonProperty("text") @ExcludeMissing private val text: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val type: JsonField, + private val text: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("text") @ExcludeMissing text: JsonField = JsonMissing.of(), + ) : this(type, text, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected value). @@ -38,7 +41,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun text(): Optional = Optional.ofNullable(text.getNullable("text")) + fun text(): Optional = text.getOptional("text") /** * Returns the raw JSON value of [type]. @@ -54,21 +57,15 @@ private constructor( */ @JsonProperty("text") @ExcludeMissing fun _text(): JsonField = text + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ChatCompletionContentPartText = apply { - if (validated) { - return@apply - } - - type() - text() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -155,10 +152,39 @@ private constructor( ChatCompletionContentPartText( checkRequired("type", type), text, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): ChatCompletionContentPartText = apply { + if (validated) { + return@apply + } + + type().validate() + text() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + (if (text.asKnown().isPresent) 1 else 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -240,6 +266,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ChatCompletionMessageToolCall.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ChatCompletionMessageToolCall.kt index 6c3fcd98..fdd8a4d7 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ChatCompletionMessageToolCall.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ChatCompletionMessageToolCall.kt @@ -7,29 +7,31 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 kotlin.jvm.optionals.getOrNull -@NoAutoDetect class ChatCompletionMessageToolCall -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("function") - @ExcludeMissing - private val function: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val function: JsonField, + private val type: JsonField, + 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: JsonField = JsonMissing.of(), + ) : this(id, function, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected value). @@ -69,22 +71,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ChatCompletionMessageToolCall = apply { - if (validated) { - return@apply - } - - id() - function().validate() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -189,24 +184,57 @@ private constructor( checkRequired("id", id), checkRequired("function", function), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): ChatCompletionMessageToolCall = apply { + if (validated) { + return@apply + } + + id() + function().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + class Function - @JsonCreator private constructor( - @JsonProperty("arguments") - @ExcludeMissing - private val arguments: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val arguments: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("arguments") + @ExcludeMissing + arguments: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(arguments, name, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected value). @@ -233,21 +261,15 @@ private constructor( */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Function = apply { - if (validated) { - return@apply - } - - arguments() - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -337,10 +359,40 @@ private constructor( Function( checkRequired("arguments", arguments), checkRequired("name", name), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Function = apply { + if (validated) { + return@apply + } + + arguments() + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -440,6 +492,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/CodeBundle.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/CodeBundle.kt index 56c5f85e..d547c7a0 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/CodeBundle.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/CodeBundle.kt @@ -9,11 +9,9 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect +import com.braintrustdata.api.core.allMaxBy import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter @@ -26,29 +24,30 @@ 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.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class CodeBundle -@JsonCreator private constructor( - @JsonProperty("bundle_id") - @ExcludeMissing - private val bundleId: JsonField = JsonMissing.of(), - @JsonProperty("location") - @ExcludeMissing - private val location: JsonField = JsonMissing.of(), - @JsonProperty("runtime_context") - @ExcludeMissing - private val runtimeContext: JsonField = JsonMissing.of(), - @JsonProperty("preview") - @ExcludeMissing - private val preview: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val bundleId: JsonField, + private val location: JsonField, + private val runtimeContext: JsonField, + private val preview: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("bundle_id") @ExcludeMissing bundleId: JsonField = JsonMissing.of(), + @JsonProperty("location") @ExcludeMissing location: JsonField = JsonMissing.of(), + @JsonProperty("runtime_context") + @ExcludeMissing + runtimeContext: JsonField = JsonMissing.of(), + @JsonProperty("preview") @ExcludeMissing preview: JsonField = JsonMissing.of(), + ) : this(bundleId, location, runtimeContext, preview, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected value). @@ -73,7 +72,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun preview(): Optional = Optional.ofNullable(preview.getNullable("preview")) + fun preview(): Optional = preview.getOptional("preview") /** * Returns the raw JSON value of [bundleId]. @@ -105,23 +104,15 @@ private constructor( */ @JsonProperty("preview") @ExcludeMissing fun _preview(): JsonField = preview + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): CodeBundle = apply { - if (validated) { - return@apply - } - - bundleId() - location().validate() - runtimeContext().validate() - preview() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -252,10 +243,44 @@ private constructor( checkRequired("location", location), checkRequired("runtimeContext", runtimeContext), preview, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): CodeBundle = apply { + if (validated) { + return@apply + } + + bundleId() + location().validate() + runtimeContext().validate() + preview() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (bundleId.asKnown().isPresent) 1 else 0) + + (location.asKnown().getOrNull()?.validity() ?: 0) + + (runtimeContext.asKnown().getOrNull()?.validity() ?: 0) + + (if (preview.asKnown().isPresent) 1 else 0) + @JsonDeserialize(using = Location.Deserializer::class) @JsonSerialize(using = Location.Serializer::class) class Location @@ -279,13 +304,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { experiment != null -> visitor.visitExperiment(experiment) function != null -> visitor.visitFunction(function) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -308,6 +332,32 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitExperiment(experiment: Experiment) = experiment.validity() + + override fun visitFunction(function: Function) = function.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -362,16 +412,28 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Location { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Location(experiment = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Location(function = it, _json = json) - } - - return Location(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Location(experiment = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Location(function = 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 -> Location(_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() + } } } @@ -391,23 +453,25 @@ private constructor( } } - @NoAutoDetect class Experiment - @JsonCreator private constructor( - @JsonProperty("eval_name") - @ExcludeMissing - private val evalName: JsonField = JsonMissing.of(), - @JsonProperty("position") - @ExcludeMissing - private val position: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val evalName: JsonField, + private val position: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("eval_name") + @ExcludeMissing + evalName: JsonField = JsonMissing.of(), + @JsonProperty("position") + @ExcludeMissing + position: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(evalName, position, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -454,22 +518,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Experiment = apply { - if (validated) { - return@apply - } - - evalName() - position().validate() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -584,10 +641,43 @@ private constructor( checkRequired("evalName", evalName), checkRequired("position", position), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Experiment = apply { + if (validated) { + return@apply + } + + evalName() + position().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (evalName.asKnown().isPresent) 1 else 0) + + (position.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + @JsonDeserialize(using = Position.Deserializer::class) @JsonSerialize(using = Position.Serializer::class) class Position @@ -611,13 +701,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { type != null -> visitor.visitType(type) scorer != null -> visitor.visitScorer(scorer) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -640,6 +729,32 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitType(type: Type) = type.validity() + + override fun visitScorer(scorer: Scorer) = scorer.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -695,16 +810,29 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Position { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Position(type = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Position(scorer = it, _json = json) - } - - return Position(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Position(type = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Position(scorer = 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 -> Position(_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() + } } } @@ -724,17 +852,19 @@ private constructor( } } - @NoAutoDetect class Type - @JsonCreator private constructor( - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of() + ) : this(type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -750,20 +880,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Type = apply { - if (validated) { - return@apply - } - - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -839,9 +964,37 @@ private constructor( * @throws IllegalStateException if any required field is unset. */ fun build(): Type = - Type(checkRequired("type", type), additionalProperties.toImmutable()) + Type(checkRequired("type", type), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + type().validate() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + class InnerType @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -934,6 +1087,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): InnerType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -965,20 +1146,23 @@ private constructor( "Type{type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Scorer - @JsonCreator private constructor( - @JsonProperty("index") - @ExcludeMissing - private val index: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val index: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("index") + @ExcludeMissing + index: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(index, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -1009,21 +1193,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Scorer = apply { - if (validated) { - return@apply - } - - index() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1117,10 +1295,41 @@ private constructor( Scorer( checkRequired("index", index), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Scorer = apply { + if (validated) { + return@apply + } + + index() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (index.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1209,6 +1418,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -1325,6 +1562,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -1356,20 +1620,19 @@ private constructor( "Experiment{evalName=$evalName, position=$position, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Function - @JsonCreator private constructor( - @JsonProperty("index") - @ExcludeMissing - private val index: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val index: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("index") @ExcludeMissing index: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(index, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -1398,21 +1661,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Function = apply { - if (validated) { - return@apply - } - - index() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1505,10 +1762,41 @@ private constructor( Function( checkRequired("index", index), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Function = apply { + if (validated) { + return@apply + } + + index() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (index.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1593,6 +1881,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -1625,20 +1940,19 @@ private constructor( } } - @NoAutoDetect class RuntimeContext - @JsonCreator private constructor( - @JsonProperty("runtime") - @ExcludeMissing - private val runtime: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val runtime: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("runtime") @ExcludeMissing runtime: JsonField = JsonMissing.of(), + @JsonProperty("version") @ExcludeMissing version: JsonField = JsonMissing.of(), + ) : this(runtime, version, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected value). @@ -1665,21 +1979,15 @@ private constructor( */ @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): RuntimeContext = apply { - if (validated) { - return@apply - } - - runtime() - version() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1769,10 +2077,41 @@ private constructor( RuntimeContext( checkRequired("runtime", runtime), checkRequired("version", version), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): RuntimeContext = apply { + if (validated) { + return@apply + } + + runtime().validate() + version() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (runtime.asKnown().getOrNull()?.validity() ?: 0) + + (if (version.asKnown().isPresent) 1 else 0) + class Runtime @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1863,6 +2202,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Runtime = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/CreateApiKeyOutput.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/CreateApiKeyOutput.kt index 24beff8e..2cbb41ce 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/CreateApiKeyOutput.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/CreateApiKeyOutput.kt @@ -6,40 +6,45 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class CreateApiKeyOutput -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("key") @ExcludeMissing private val key: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("preview_name") - @ExcludeMissing - private val previewName: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("org_id") @ExcludeMissing private val orgId: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val key: JsonField, + private val name: JsonField, + private val previewName: JsonField, + private val created: JsonField, + private val orgId: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("key") @ExcludeMissing key: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("preview_name") + @ExcludeMissing + previewName: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("org_id") @ExcludeMissing orgId: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this(id, key, name, previewName, created, orgId, userId, mutableMapOf()) + /** * Unique identifier for the api key * @@ -76,7 +81,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Unique identifier for the organization @@ -84,7 +89,7 @@ private constructor( * @throws BraintrustInvalidDataException 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 orgId(): Optional = orgId.getOptional("org_id") /** * Unique identifier for the user @@ -92,7 +97,7 @@ private constructor( * @throws BraintrustInvalidDataException 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 [id]. @@ -145,26 +150,15 @@ private constructor( */ @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 = additionalProperties - - private var validated: Boolean = false - - fun validate(): CreateApiKeyOutput = apply { - if (validated) { - return@apply - } - - id() - key() - name() - previewName() - created() - orgId() - userId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -338,10 +332,50 @@ private constructor( created, orgId, userId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): CreateApiKeyOutput = apply { + if (validated) { + return@apply + } + + id() + key() + name() + previewName() + created() + orgId() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (key.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (previewName.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (orgId.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/CrossObjectInsertResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/CrossObjectInsertResponse.kt index 2b7bead1..e258e247 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/CrossObjectInsertResponse.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/CrossObjectInsertResponse.kt @@ -6,41 +6,43 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 -@NoAutoDetect class CrossObjectInsertResponse -@JsonCreator private constructor( - @JsonProperty("dataset") - @ExcludeMissing - private val dataset: JsonField = JsonMissing.of(), - @JsonProperty("experiment") - @ExcludeMissing - private val experiment: JsonField = JsonMissing.of(), - @JsonProperty("project_logs") - @ExcludeMissing - private val projectLogs: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val dataset: JsonField, + private val experiment: JsonField, + private val projectLogs: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("dataset") @ExcludeMissing dataset: JsonField = JsonMissing.of(), + @JsonProperty("experiment") + @ExcludeMissing + experiment: JsonField = JsonMissing.of(), + @JsonProperty("project_logs") + @ExcludeMissing + projectLogs: JsonField = JsonMissing.of(), + ) : this(dataset, experiment, projectLogs, mutableMapOf()) + /** * A mapping from dataset id to row ids for inserted `events` * * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun dataset(): Optional = Optional.ofNullable(dataset.getNullable("dataset")) + fun dataset(): Optional = dataset.getOptional("dataset") /** * A mapping from experiment id to row ids for inserted `events` @@ -48,8 +50,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun experiment(): Optional = - Optional.ofNullable(experiment.getNullable("experiment")) + fun experiment(): Optional = experiment.getOptional("experiment") /** * A mapping from project id to row ids for inserted `events` @@ -57,8 +58,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun projectLogs(): Optional = - Optional.ofNullable(projectLogs.getNullable("project_logs")) + fun projectLogs(): Optional = projectLogs.getOptional("project_logs") /** * Returns the raw JSON value of [dataset]. @@ -85,22 +85,15 @@ private constructor( @ExcludeMissing fun _projectLogs(): JsonField = projectLogs + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): CrossObjectInsertResponse = apply { - if (validated) { - return@apply - } - - dataset().ifPresent { it.validate() } - experiment().ifPresent { it.validate() } - projectLogs().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -203,33 +196,54 @@ private constructor( dataset, experiment, projectLogs, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): CrossObjectInsertResponse = apply { + if (validated) { + return@apply + } + + dataset().ifPresent { it.validate() } + experiment().ifPresent { it.validate() } + projectLogs().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (dataset.asKnown().getOrNull()?.validity() ?: 0) + + (experiment.asKnown().getOrNull()?.validity() ?: 0) + + (projectLogs.asKnown().getOrNull()?.validity() ?: 0) + /** A mapping from dataset id to row ids for inserted `events` */ - @NoAutoDetect class Dataset @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Dataset = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -275,6 +289,34 @@ private constructor( fun build(): Dataset = Dataset(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Dataset = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -293,28 +335,17 @@ private constructor( } /** A mapping from experiment id to row ids for inserted `events` */ - @NoAutoDetect class Experiment @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Experiment = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -360,6 +391,34 @@ private constructor( fun build(): Experiment = Experiment(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Experiment = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -378,28 +437,17 @@ private constructor( } /** A mapping from project id to row ids for inserted `events` */ - @NoAutoDetect class ProjectLogs @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): ProjectLogs = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -445,6 +493,34 @@ private constructor( fun build(): ProjectLogs = ProjectLogs(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): ProjectLogs = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DataSummary.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DataSummary.kt index cdcf9fe8..e499cfa4 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DataSummary.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DataSummary.kt @@ -6,28 +6,29 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 /** Summary of a dataset's data */ -@NoAutoDetect class DataSummary -@JsonCreator private constructor( - @JsonProperty("total_records") - @ExcludeMissing - private val totalRecords: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val totalRecords: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("total_records") + @ExcludeMissing + totalRecords: JsonField = JsonMissing.of() + ) : this(totalRecords, mutableMapOf()) + /** * Total number of records in the dataset * @@ -45,20 +46,15 @@ private constructor( @ExcludeMissing fun _totalRecords(): JsonField = totalRecords + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): DataSummary = apply { - if (validated) { - return@apply - } - - totalRecords() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -133,10 +129,36 @@ private constructor( fun build(): DataSummary = DataSummary( checkRequired("totalRecords", totalRecords), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): DataSummary = apply { + if (validated) { + return@apply + } + + totalRecords() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (totalRecords.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Dataset.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Dataset.kt index e0a65784..66fafea8 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Dataset.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Dataset.kt @@ -6,9 +6,7 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -16,37 +14,42 @@ import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class Dataset -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("deleted_at") - @ExcludeMissing - private val deletedAt: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val name: JsonField, + private val projectId: JsonField, + private val created: JsonField, + private val deletedAt: JsonField, + private val description: JsonField, + private val metadata: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") @ExcludeMissing projectId: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("deleted_at") + @ExcludeMissing + deletedAt: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this(id, name, projectId, created, deletedAt, description, metadata, userId, mutableMapOf()) + /** * Unique identifier for the dataset * @@ -77,7 +80,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Date of dataset deletion, or null if the dataset is still active @@ -85,8 +88,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun deletedAt(): Optional = - Optional.ofNullable(deletedAt.getNullable("deleted_at")) + fun deletedAt(): Optional = deletedAt.getOptional("deleted_at") /** * Textual description of the dataset @@ -94,8 +96,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun description(): Optional = description.getOptional("description") /** * User-controlled metadata about the dataset @@ -103,7 +104,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** * Identifies the user who created the dataset @@ -111,7 +112,7 @@ private constructor( * @throws BraintrustInvalidDataException 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 [id]. @@ -171,27 +172,15 @@ private constructor( */ @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 = additionalProperties - - private var validated: Boolean = false - - fun validate(): Dataset = apply { - if (validated) { - return@apply - } - - id() - name() - projectId() - created() - deletedAt() - description() - metadata().ifPresent { it.validate() } - userId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -387,33 +376,64 @@ private constructor( description, metadata, userId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Dataset = apply { + if (validated) { + return@apply + } + + id() + name() + projectId() + created() + deletedAt() + description() + metadata().ifPresent { it.validate() } + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (deletedAt.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (userId.asKnown().isPresent) 1 else 0) + /** User-controlled metadata about the dataset */ - @NoAutoDetect class Metadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -459,6 +479,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetCreateParams.kt index fb4cd2c4..b082caaa 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetCreateParams.kt @@ -6,18 +6,17 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -99,263 +98,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * Name of the dataset. Within a project, dataset names are unique - * - * @throws BraintrustInvalidDataException 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") - - /** - * Unique identifier for the project that the dataset belongs under - * - * @throws BraintrustInvalidDataException 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 projectId(): String = projectId.getRequired("project_id") - - /** - * Textual description of the dataset - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - /** - * User-controlled metadata about the dataset - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) - - /** - * 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 [projectId]. - * - * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId - - /** - * Returns the raw JSON value of [description]. - * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description - - /** - * Returns the raw JSON value of [metadata]. - * - * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - name() - projectId() - description() - metadata().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var name: JsonField? = null - private var projectId: JsonField? = null - private var description: JsonField = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - projectId = body.projectId - description = body.description - metadata = body.metadata - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** Name of the dataset. Within a project, dataset names are unique */ - 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 } - - /** Unique identifier for the project that the dataset belongs under */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - - /** - * Sets [Builder.projectId] to an arbitrary JSON value. - * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } - - /** Textual description of the dataset */ - fun description(description: String?) = description(JsonField.ofNullable(description)) - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } - - /** User-controlled metadata about the dataset */ - 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 additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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 - * .name() - * .projectId() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("name", name), - checkRequired("projectId", projectId), - description, - metadata, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && description == other.description && metadata == other.metadata && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, projectId, description, metadata, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{name=$name, projectId=$projectId, description=$description, metadata=$metadata, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -373,7 +115,6 @@ private constructor( } /** A builder for [DatasetCreateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -387,6 +128,18 @@ private constructor( additionalQueryParams = datasetCreateParams.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: + * - [name] + * - [projectId] + * - [description] + * - [metadata] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** Name of the dataset. Within a project, dataset names are unique */ fun name(name: String) = apply { body.name(name) } @@ -578,29 +331,304 @@ private constructor( ) } - /** User-controlled metadata about the dataset */ - @NoAutoDetect - class Metadata - @JsonCreator + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + private val name: JsonField, + private val projectId: JsonField, + private val description: JsonField, + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") + @ExcludeMissing + projectId: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), + ) : this(name, projectId, description, metadata, mutableMapOf()) + + /** + * Name of the dataset. Within a project, dataset names are unique + * + * @throws BraintrustInvalidDataException 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") + + /** + * Unique identifier for the project that the dataset belongs under + * + * @throws BraintrustInvalidDataException 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 projectId(): String = projectId.getRequired("project_id") + + /** + * Textual description of the dataset + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * User-controlled metadata about the dataset + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * 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 [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + 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 + * .name() + * .projectId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var projectId: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + projectId = body.projectId + description = body.description + metadata = body.metadata + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the dataset. Within a project, dataset names are unique */ + 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 } + + /** Unique identifier for the project that the dataset belongs under */ + fun projectId(projectId: String) = projectId(JsonField.of(projectId)) + + /** + * Sets [Builder.projectId] to an arbitrary JSON value. + * + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun projectId(projectId: JsonField) = apply { this.projectId = projectId } + + /** Textual description of the dataset */ + fun description(description: String?) = description(JsonField.ofNullable(description)) + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + + /** User-controlled metadata about the dataset */ + 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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 + * .name() + * .projectId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("name", name), + checkRequired("projectId", projectId), + description, + metadata, + additionalProperties.toMutableMap(), + ) + } private var validated: Boolean = false - fun validate(): Metadata = apply { + fun validate(): Body = apply { if (validated) { return@apply } + name() + projectId() + description() + metadata().ifPresent { it.validate() } validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && description == other.description && metadata == other.metadata && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, projectId, description, metadata, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, projectId=$projectId, description=$description, metadata=$metadata, additionalProperties=$additionalProperties}" + } + + /** User-controlled metadata about the dataset */ + 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 { @@ -646,6 +674,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetDeleteParams.kt index 67c7b316..c4238c34 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetDeleteParams.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,26 +23,11 @@ private constructor( /** Dataset id */ fun datasetId(): String = datasetId - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> datasetId - else -> "" - } - } + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -61,7 +45,6 @@ private constructor( } /** A builder for [DatasetDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var datasetId: String? = null @@ -221,6 +204,19 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> datasetId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetEvent.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetEvent.kt index 28bf576a..e3b2abfa 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetEvent.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetEvent.kt @@ -6,10 +6,8 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -17,50 +15,67 @@ import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class DatasetEvent -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("_xact_id") - @ExcludeMissing - private val _xactId: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("dataset_id") - @ExcludeMissing - private val datasetId: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("root_span_id") - @ExcludeMissing - private val rootSpanId: JsonField = JsonMissing.of(), - @JsonProperty("span_id") - @ExcludeMissing - private val spanId: JsonField = JsonMissing.of(), - @JsonProperty("expected") @ExcludeMissing private val expected: JsonValue = JsonMissing.of(), - @JsonProperty("input") @ExcludeMissing private val input: JsonValue = JsonMissing.of(), - @JsonProperty("is_root") - @ExcludeMissing - private val isRoot: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("origin") - @ExcludeMissing - private val origin: JsonField = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val _xactId: JsonField, + private val created: JsonField, + private val datasetId: JsonField, + private val projectId: JsonField, + private val rootSpanId: JsonField, + private val spanId: JsonField, + private val expected: JsonValue, + private val input: JsonValue, + private val isRoot: JsonField, + private val metadata: JsonField, + private val origin: JsonField, + private val tags: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("_xact_id") @ExcludeMissing _xactId: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("dataset_id") @ExcludeMissing datasetId: JsonField = JsonMissing.of(), + @JsonProperty("project_id") @ExcludeMissing projectId: JsonField = JsonMissing.of(), + @JsonProperty("root_span_id") + @ExcludeMissing + rootSpanId: JsonField = JsonMissing.of(), + @JsonProperty("span_id") @ExcludeMissing spanId: JsonField = JsonMissing.of(), + @JsonProperty("expected") @ExcludeMissing expected: JsonValue = JsonMissing.of(), + @JsonProperty("input") @ExcludeMissing input: JsonValue = JsonMissing.of(), + @JsonProperty("is_root") @ExcludeMissing isRoot: JsonField = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("origin") + @ExcludeMissing + origin: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this( + id, + _xactId, + created, + datasetId, + projectId, + rootSpanId, + spanId, + expected, + input, + isRoot, + metadata, + origin, + tags, + mutableMapOf(), + ) + /** * A unique identifier for the dataset event. If you don't provide one, BrainTrust will generate * one for you @@ -137,7 +152,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun isRoot(): Optional = Optional.ofNullable(isRoot.getNullable("is_root")) + fun isRoot(): Optional = isRoot.getOptional("is_root") /** * A dictionary with additional data about the test example, model outputs, or just about @@ -149,7 +164,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** * Indicates the event was copied from another object. @@ -157,7 +172,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun origin(): Optional = Optional.ofNullable(origin.getNullable("origin")) + fun origin(): Optional = origin.getOptional("origin") /** * A list of tags to log @@ -165,7 +180,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [id]. @@ -244,30 +259,15 @@ private constructor( */ @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): DatasetEvent = apply { - if (validated) { - return@apply - } - - id() - _xactId() - created() - datasetId() - projectId() - rootSpanId() - spanId() - isRoot() - metadata().ifPresent { it.validate() } - origin().ifPresent { it.validate() } - tags() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -564,10 +564,58 @@ private constructor( metadata, origin, (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): DatasetEvent = apply { + if (validated) { + return@apply + } + + id() + _xactId() + created() + datasetId() + projectId() + rootSpanId() + spanId() + isRoot() + metadata().ifPresent { it.validate() } + origin().ifPresent { it.validate() } + tags() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (_xactId.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (datasetId.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (rootSpanId.asKnown().isPresent) 1 else 0) + + (if (spanId.asKnown().isPresent) 1 else 0) + + (if (isRoot.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (origin.asKnown().getOrNull()?.validity() ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + /** * A dictionary with additional data about the test example, model outputs, or just about * anything else that's relevant, that you can use to help find and analyze examples later. For @@ -575,24 +623,24 @@ private constructor( * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys * must be strings */ - @NoAutoDetect class Metadata - @JsonCreator private constructor( - @JsonProperty("model") - @ExcludeMissing - private val model: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val model: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of() + ) : this(model, mutableMapOf()) + /** * The model used for this example * * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [model]. @@ -601,20 +649,15 @@ private constructor( */ @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - model() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -675,9 +718,36 @@ private constructor( * * Further updates to this [Builder] will not mutate the returned instance. */ - fun build(): Metadata = Metadata(model, additionalProperties.toImmutable()) + fun build(): Metadata = Metadata(model, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + model() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFeedbackParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFeedbackParams.kt index bb641fb0..e313cd08 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFeedbackParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFeedbackParams.kt @@ -6,20 +6,20 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 kotlin.jvm.optionals.getOrNull /** Log feedback for a set of dataset events */ class DatasetFeedbackParams @@ -54,171 +54,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> datasetId - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("feedback") - @ExcludeMissing - private val feedback: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * A list of dataset feedback items - * - * @throws BraintrustInvalidDataException 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 feedback(): List = feedback.getRequired("feedback") - - /** - * Returns the raw JSON value of [feedback]. - * - * Unlike [feedback], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("feedback") - @ExcludeMissing - fun _feedback(): JsonField> = feedback - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - feedback().forEach { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .feedback() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var feedback: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - feedback = body.feedback.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** A list of dataset feedback items */ - fun feedback(feedback: List) = feedback(JsonField.of(feedback)) - - /** - * Sets [Builder.feedback] to an arbitrary JSON value. - * - * You should usually call [Builder.feedback] with a well-typed - * `List` value instead. This method is primarily for setting the - * field to an undocumented or not yet supported value. - */ - fun feedback(feedback: JsonField>) = apply { - this.feedback = feedback.map { it.toMutableList() } - } - - /** - * Adds a single [FeedbackDatasetItem] to [Builder.feedback]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addFeedback(feedback: FeedbackDatasetItem) = apply { - this.feedback = - (this.feedback ?: JsonField.of(mutableListOf())).also { - checkKnown("feedback", it).add(feedback) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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 - * .feedback() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("feedback", feedback).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && feedback == other.feedback && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(feedback, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{feedback=$feedback, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -236,7 +71,6 @@ private constructor( } /** A builder for [DatasetFeedbackParams]. */ - @NoAutoDetect class Builder internal constructor() { private var datasetId: String? = null @@ -255,6 +89,15 @@ private constructor( /** Dataset id */ fun datasetId(datasetId: String) = apply { this.datasetId = datasetId } + /** + * 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: + * - [feedback] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** A list of dataset feedback items */ fun feedback(feedback: List) = apply { body.feedback(feedback) } @@ -415,6 +258,196 @@ private constructor( ) } + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> datasetId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val feedback: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("feedback") + @ExcludeMissing + feedback: JsonField> = JsonMissing.of() + ) : this(feedback, mutableMapOf()) + + /** + * A list of dataset feedback items + * + * @throws BraintrustInvalidDataException 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 feedback(): List = feedback.getRequired("feedback") + + /** + * Returns the raw JSON value of [feedback]. + * + * Unlike [feedback], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("feedback") + @ExcludeMissing + fun _feedback(): JsonField> = feedback + + @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 + * .feedback() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var feedback: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + feedback = body.feedback.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** A list of dataset feedback items */ + fun feedback(feedback: List) = feedback(JsonField.of(feedback)) + + /** + * Sets [Builder.feedback] to an arbitrary JSON value. + * + * You should usually call [Builder.feedback] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun feedback(feedback: JsonField>) = apply { + this.feedback = feedback.map { it.toMutableList() } + } + + /** + * Adds a single [FeedbackDatasetItem] to [Builder.feedback]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFeedback(feedback: FeedbackDatasetItem) = apply { + this.feedback = + (this.feedback ?: JsonField.of(mutableListOf())).also { + checkKnown("feedback", it).add(feedback) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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 + * .feedback() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("feedback", feedback).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + feedback().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (feedback.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && feedback == other.feedback && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(feedback, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{feedback=$feedback, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFetchParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFetchParams.kt index b00ce504..ac9b82f8 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFetchParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFetchParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -86,26 +85,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - limit?.let { put("limit", it.toString()) } - maxRootSpanId?.let { put("max_root_span_id", it) } - maxXactId?.let { put("max_xact_id", it) } - version?.let { put("version", it) } - putAll(additionalQueryParams) - } - .build() - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> datasetId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -122,7 +101,6 @@ private constructor( } /** A builder for [DatasetFetchParams]. */ - @NoAutoDetect class Builder internal constructor() { private var datasetId: String? = null @@ -342,6 +320,25 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> datasetId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + limit?.let { put("limit", it.toString()) } + maxRootSpanId?.let { put("max_root_span_id", it) } + maxXactId?.let { put("max_xact_id", it) } + version?.let { put("version", it) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFetchPostParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFetchPostParams.kt index b829eb13..6dd48c3a 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFetchPostParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFetchPostParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -154,41 +152,53 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) - override fun _headers(): Headers = additionalHeaders + companion object { - override fun _queryParams(): QueryParams = additionalQueryParams + /** + * Returns a mutable builder for constructing an instance of [DatasetFetchPostParams]. + * + * The following fields are required: + * ```java + * .datasetId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - fun getPathParam(index: Int): String { - return when (index) { - 0 -> datasetId - else -> "" + /** A builder for [DatasetFetchPostParams]. */ + class Builder internal constructor() { + + private var datasetId: 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(datasetFetchPostParams: DatasetFetchPostParams) = apply { + datasetId = datasetFetchPostParams.datasetId + body = datasetFetchPostParams.body.toBuilder() + additionalHeaders = datasetFetchPostParams.additionalHeaders.toBuilder() + additionalQueryParams = datasetFetchPostParams.additionalQueryParams.toBuilder() } - } - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("cursor") - @ExcludeMissing - private val cursor: JsonField = JsonMissing.of(), - @JsonProperty("limit") - @ExcludeMissing - private val limit: JsonField = JsonMissing.of(), - @JsonProperty("max_root_span_id") - @ExcludeMissing - private val maxRootSpanId: JsonField = JsonMissing.of(), - @JsonProperty("max_xact_id") - @ExcludeMissing - private val maxXactId: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** Dataset id */ + fun datasetId(datasetId: String) = apply { this.datasetId = datasetId } + + /** + * 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: + * - [cursor] + * - [limit] + * - [maxRootSpanId] + * - [maxXactId] + * - [version] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } /** * An opaque string to be used as a cursor for the next page of results, in order from @@ -196,11 +206,19 @@ private constructor( * * The string can be obtained directly from the `cursor` property of the previous fetch * query + */ + fun cursor(cursor: String?) = apply { body.cursor(cursor) } + + /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ + fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) + + /** + * Sets [Builder.cursor] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.cursor] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - fun cursor(): Optional = Optional.ofNullable(cursor.getNullable("cursor")) + fun cursor(cursor: JsonField) = apply { body.cursor(cursor) } /** * limit the number of traces fetched @@ -216,11 +234,26 @@ private constructor( * The `limit` parameter controls the number of full traces to return. So you may end up * with more individual rows than the specified limit if you are fetching events containing * traces. + */ + fun limit(limit: Long?) = apply { body.limit(limit) } + + /** + * Alias for [Builder.limit]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * This unboxed primitive overload exists for backwards compatibility. + */ + fun limit(limit: Long) = limit(limit as Long?) + + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) + + /** + * Sets [Builder.limit] to an arbitrary JSON value. + * + * You should usually call [Builder.limit] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - fun limit(): Optional = Optional.ofNullable(limit.getNullable("limit")) + fun limit(limit: JsonField) = apply { body.limit(limit) } /** * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor of @@ -233,12 +266,23 @@ private constructor( * cursor for the next page can be found as the row with the minimum (earliest) value of the * tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an overview of * paginating fetch queries. + */ + fun maxRootSpanId(maxRootSpanId: String?) = apply { body.maxRootSpanId(maxRootSpanId) } + + /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ + fun maxRootSpanId(maxRootSpanId: Optional) = + maxRootSpanId(maxRootSpanId.getOrNull()) + + /** + * Sets [Builder.maxRootSpanId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.maxRootSpanId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun maxRootSpanId(): Optional = - Optional.ofNullable(maxRootSpanId.getNullable("max_root_span_id")) + fun maxRootSpanId(maxRootSpanId: JsonField) = apply { + body.maxRootSpanId(maxRootSpanId) + } /** * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor of @@ -251,330 +295,212 @@ private constructor( * cursor for the next page can be found as the row with the minimum (earliest) value of the * tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an overview of * paginating fetch queries. + */ + fun maxXactId(maxXactId: String?) = apply { body.maxXactId(maxXactId) } + + /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ + fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) + + /** + * Sets [Builder.maxXactId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.maxXactId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun maxXactId(): Optional = - Optional.ofNullable(maxXactId.getNullable("max_xact_id")) + fun maxXactId(maxXactId: JsonField) = apply { body.maxXactId(maxXactId) } /** * Retrieve a snapshot of events from a past time * * The version id is essentially a filter on the latest event transaction id. You can use * the `max_xact_id` returned by a past fetch as the version to reproduce that exact fetch. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). */ - fun version(): Optional = Optional.ofNullable(version.getNullable("version")) + fun version(version: String?) = apply { body.version(version) } - /** - * Returns the raw JSON value of [cursor]. - * - * Unlike [cursor], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("cursor") @ExcludeMissing fun _cursor(): JsonField = cursor + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) /** - * Returns the raw JSON value of [limit]. + * Sets [Builder.version] to an arbitrary JSON value. * - * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.version] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit + fun version(version: JsonField) = apply { body.version(version) } - /** - * Returns the raw JSON value of [maxRootSpanId]. - * - * Unlike [maxRootSpanId], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("max_root_span_id") - @ExcludeMissing - fun _maxRootSpanId(): JsonField = maxRootSpanId + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - /** - * Returns the raw JSON value of [maxXactId]. - * - * Unlike [maxXactId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("max_xact_id") @ExcludeMissing fun _maxXactId(): JsonField = maxXactId + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - /** - * Returns the raw JSON value of [version]. - * - * Unlike [version], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - private var validated: Boolean = false + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - fun validate(): Body = apply { - if (validated) { - return@apply - } + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - cursor() - limit() - maxRootSpanId() - maxXactId() - version() - validated = true + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun toBuilder() = Builder().from(this) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - companion object { + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** Returns a mutable builder for constructing an instance of [Body]. */ - @JvmStatic fun builder() = Builder() + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - private var cursor: JsonField = JsonMissing.of() - private var limit: JsonField = JsonMissing.of() - private var maxRootSpanId: JsonField = JsonMissing.of() - private var maxXactId: JsonField = JsonMissing.of() - private var version: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - @JvmSynthetic - internal fun from(body: Body) = apply { - cursor = body.cursor - limit = body.limit - maxRootSpanId = body.maxRootSpanId - maxXactId = body.maxXactId - version = body.version - additionalProperties = body.additionalProperties.toMutableMap() - } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** - * An opaque string to be used as a cursor for the next page of results, in order from - * latest to earliest. - * - * The string can be obtained directly from the `cursor` property of the previous fetch - * query - */ - fun cursor(cursor: String?) = cursor(JsonField.ofNullable(cursor)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ - fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.cursor] to an arbitrary JSON value. - * - * You should usually call [Builder.cursor] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun cursor(cursor: JsonField) = apply { this.cursor = cursor } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - /** - * limit the number of traces fetched - * - * Fetch queries may be paginated if the total result size is expected to be large (e.g. - * project_logs which accumulate over a long time). Note that fetch queries only support - * pagination in descending time order (from latest to earliest `_xact_id`. Furthermore, - * later pages may return rows which showed up in earlier pages, except with an earlier - * `_xact_id`. This happens because pagination occurs over the whole version history of - * the event log. You will most likely want to exclude any such duplicate, outdated rows - * (by `id`) from your combined result set. - * - * The `limit` parameter controls the number of full traces to return. So you may end up - * with more individual rows than the specified limit if you are fetching events - * containing traces. - */ - fun limit(limit: Long?) = limit(JsonField.ofNullable(limit)) - - /** - * Alias for [Builder.limit]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun limit(limit: Long) = limit(limit as Long?) - - /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ - fun limit(limit: Optional) = limit(limit.getOrNull()) - - /** - * Sets [Builder.limit] to an arbitrary JSON value. - * - * You should usually call [Builder.limit] with a well-typed [Long] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun limit(limit: JsonField) = apply { this.limit = limit } - - /** - * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor - * of the explicit 'cursor' returned by object fetch requests. Please prefer the - * 'cursor' argument going forwards. - * - * Together, `max_xact_id` and `max_root_span_id` form a pagination cursor - * - * Since a paginated fetch query returns results in order from latest to earliest, the - * cursor for the next page can be found as the row with the minimum (earliest) value of - * the tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an - * overview of paginating fetch queries. - */ - fun maxRootSpanId(maxRootSpanId: String?) = - maxRootSpanId(JsonField.ofNullable(maxRootSpanId)) - - /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ - fun maxRootSpanId(maxRootSpanId: Optional) = - maxRootSpanId(maxRootSpanId.getOrNull()) - - /** - * Sets [Builder.maxRootSpanId] to an arbitrary JSON value. - * - * You should usually call [Builder.maxRootSpanId] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun maxRootSpanId(maxRootSpanId: JsonField) = apply { - this.maxRootSpanId = maxRootSpanId - } - - /** - * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor - * of the explicit 'cursor' returned by object fetch requests. Please prefer the - * 'cursor' argument going forwards. - * - * Together, `max_xact_id` and `max_root_span_id` form a pagination cursor - * - * Since a paginated fetch query returns results in order from latest to earliest, the - * cursor for the next page can be found as the row with the minimum (earliest) value of - * the tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an - * overview of paginating fetch queries. - */ - fun maxXactId(maxXactId: String?) = maxXactId(JsonField.ofNullable(maxXactId)) - - /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ - fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) - - /** - * Sets [Builder.maxXactId] to an arbitrary JSON value. - * - * You should usually call [Builder.maxXactId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun maxXactId(maxXactId: JsonField) = apply { this.maxXactId = maxXactId } - - /** - * Retrieve a snapshot of events from a past time - * - * The version id is essentially a filter on the latest event transaction id. You can - * use the `max_xact_id` returned by a past fetch as the version to reproduce that exact - * fetch. - */ - fun version(version: String?) = version(JsonField.ofNullable(version)) - - /** Alias for calling [Builder.version] with `version.orElse(null)`. */ - fun version(version: Optional) = version(version.getOrNull()) - - /** - * Sets [Builder.version] to an arbitrary JSON value. - * - * You should usually call [Builder.version] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun version(version: JsonField) = apply { this.version = version } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Body = - Body( - cursor, - limit, - maxRootSpanId, - maxXactId, - version, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && cursor == other.cursor && limit == other.limit && maxRootSpanId == other.maxRootSpanId && maxXactId == other.maxXactId && version == other.version && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(cursor, limit, maxRootSpanId, maxXactId, version, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{cursor=$cursor, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [DatasetFetchPostParams]. + * Returns an immutable instance of [DatasetFetchPostParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java * .datasetId() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): DatasetFetchPostParams = + DatasetFetchPostParams( + checkRequired("datasetId", datasetId), + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [DatasetFetchPostParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var datasetId: String? = null - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + fun _body(): Body = body - @JvmSynthetic - internal fun from(datasetFetchPostParams: DatasetFetchPostParams) = apply { - datasetId = datasetFetchPostParams.datasetId - body = datasetFetchPostParams.body.toBuilder() - additionalHeaders = datasetFetchPostParams.additionalHeaders.toBuilder() - additionalQueryParams = datasetFetchPostParams.additionalQueryParams.toBuilder() + fun _pathParam(index: Int): String = + when (index) { + 0 -> datasetId + else -> "" } - /** Dataset id */ - fun datasetId(datasetId: String) = apply { this.datasetId = datasetId } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val cursor: JsonField, + private val limit: JsonField, + private val maxRootSpanId: JsonField, + private val maxXactId: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("cursor") @ExcludeMissing cursor: JsonField = JsonMissing.of(), + @JsonProperty("limit") @ExcludeMissing limit: JsonField = JsonMissing.of(), + @JsonProperty("max_root_span_id") + @ExcludeMissing + maxRootSpanId: JsonField = JsonMissing.of(), + @JsonProperty("max_xact_id") + @ExcludeMissing + maxXactId: JsonField = JsonMissing.of(), + @JsonProperty("version") @ExcludeMissing version: JsonField = JsonMissing.of(), + ) : this(cursor, limit, maxRootSpanId, maxXactId, version, mutableMapOf()) /** * An opaque string to be used as a cursor for the next page of results, in order from @@ -582,19 +508,11 @@ private constructor( * * The string can be obtained directly from the `cursor` property of the previous fetch * query - */ - fun cursor(cursor: String?) = apply { body.cursor(cursor) } - - /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ - fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) - - /** - * Sets [Builder.cursor] to an arbitrary JSON value. * - * You should usually call [Builder.cursor] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun cursor(cursor: JsonField) = apply { body.cursor(cursor) } + fun cursor(): Optional = cursor.getOptional("cursor") /** * limit the number of traces fetched @@ -610,26 +528,11 @@ private constructor( * The `limit` parameter controls the number of full traces to return. So you may end up * with more individual rows than the specified limit if you are fetching events containing * traces. - */ - fun limit(limit: Long?) = apply { body.limit(limit) } - - /** - * Alias for [Builder.limit]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun limit(limit: Long) = limit(limit as Long?) - - /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ - fun limit(limit: Optional) = limit(limit.getOrNull()) - - /** - * Sets [Builder.limit] to an arbitrary JSON value. * - * You should usually call [Builder.limit] with a well-typed [Long] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun limit(limit: JsonField) = apply { body.limit(limit) } + fun limit(): Optional = limit.getOptional("limit") /** * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor of @@ -642,23 +545,11 @@ private constructor( * cursor for the next page can be found as the row with the minimum (earliest) value of the * tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an overview of * paginating fetch queries. - */ - fun maxRootSpanId(maxRootSpanId: String?) = apply { body.maxRootSpanId(maxRootSpanId) } - - /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ - fun maxRootSpanId(maxRootSpanId: Optional) = - maxRootSpanId(maxRootSpanId.getOrNull()) - - /** - * Sets [Builder.maxRootSpanId] to an arbitrary JSON value. * - * You should usually call [Builder.maxRootSpanId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun maxRootSpanId(maxRootSpanId: JsonField) = apply { - body.maxRootSpanId(maxRootSpanId) - } + fun maxRootSpanId(): Optional = maxRootSpanId.getOptional("max_root_span_id") /** * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor of @@ -671,176 +562,321 @@ private constructor( * cursor for the next page can be found as the row with the minimum (earliest) value of the * tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an overview of * paginating fetch queries. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun maxXactId(maxXactId: String?) = apply { body.maxXactId(maxXactId) } + fun maxXactId(): Optional = maxXactId.getOptional("max_xact_id") - /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ - fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) + /** + * Retrieve a snapshot of events from a past time + * + * The version id is essentially a filter on the latest event transaction id. You can use + * the `max_xact_id` returned by a past fetch as the version to reproduce that exact fetch. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun version(): Optional = version.getOptional("version") /** - * Sets [Builder.maxXactId] to an arbitrary JSON value. + * Returns the raw JSON value of [cursor]. * - * You should usually call [Builder.maxXactId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [cursor], this method doesn't throw if the JSON field has an unexpected type. */ - fun maxXactId(maxXactId: JsonField) = apply { body.maxXactId(maxXactId) } + @JsonProperty("cursor") @ExcludeMissing fun _cursor(): JsonField = cursor /** - * Retrieve a snapshot of events from a past time + * Returns the raw JSON value of [limit]. * - * The version id is essentially a filter on the latest event transaction id. You can use - * the `max_xact_id` returned by a past fetch as the version to reproduce that exact fetch. + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. */ - fun version(version: String?) = apply { body.version(version) } + @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit - /** Alias for calling [Builder.version] with `version.orElse(null)`. */ - fun version(version: Optional) = version(version.getOrNull()) + /** + * Returns the raw JSON value of [maxRootSpanId]. + * + * Unlike [maxRootSpanId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("max_root_span_id") + @ExcludeMissing + fun _maxRootSpanId(): JsonField = maxRootSpanId /** - * Sets [Builder.version] to an arbitrary JSON value. + * Returns the raw JSON value of [maxXactId]. * - * You should usually call [Builder.version] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [maxXactId], this method doesn't throw if the JSON field has an unexpected type. */ - fun version(version: JsonField) = apply { body.version(version) } + @JsonProperty("max_xact_id") @ExcludeMissing fun _maxXactId(): JsonField = maxXactId - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) - } + /** + * Returns the raw JSON value of [version]. + * + * Unlike [version], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) - } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + fun toBuilder() = Builder().from(this) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + companion object { - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** A builder for [Body]. */ + class Builder internal constructor() { - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + private var cursor: JsonField = JsonMissing.of() + private var limit: JsonField = JsonMissing.of() + private var maxRootSpanId: JsonField = JsonMissing.of() + private var maxXactId: JsonField = JsonMissing.of() + private var version: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + @JvmSynthetic + internal fun from(body: Body) = apply { + cursor = body.cursor + limit = body.limit + maxRootSpanId = body.maxRootSpanId + maxXactId = body.maxXactId + version = body.version + additionalProperties = body.additionalProperties.toMutableMap() + } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * An opaque string to be used as a cursor for the next page of results, in order from + * latest to earliest. + * + * The string can be obtained directly from the `cursor` property of the previous fetch + * query + */ + fun cursor(cursor: String?) = cursor(JsonField.ofNullable(cursor)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ + fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.cursor] to an arbitrary JSON value. + * + * You should usually call [Builder.cursor] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun cursor(cursor: JsonField) = apply { this.cursor = cursor } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** + * limit the number of traces fetched + * + * Fetch queries may be paginated if the total result size is expected to be large (e.g. + * project_logs which accumulate over a long time). Note that fetch queries only support + * pagination in descending time order (from latest to earliest `_xact_id`. Furthermore, + * later pages may return rows which showed up in earlier pages, except with an earlier + * `_xact_id`. This happens because pagination occurs over the whole version history of + * the event log. You will most likely want to exclude any such duplicate, outdated rows + * (by `id`) from your combined result set. + * + * The `limit` parameter controls the number of full traces to return. So you may end up + * with more individual rows than the specified limit if you are fetching events + * containing traces. + */ + fun limit(limit: Long?) = limit(JsonField.ofNullable(limit)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun limit(limit: Long) = limit(limit as Long?) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + /** + * Sets [Builder.limit] to an arbitrary JSON value. + * + * You should usually call [Builder.limit] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun limit(limit: JsonField) = apply { this.limit = limit } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + /** + * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor + * of the explicit 'cursor' returned by object fetch requests. Please prefer the + * 'cursor' argument going forwards. + * + * Together, `max_xact_id` and `max_root_span_id` form a pagination cursor + * + * Since a paginated fetch query returns results in order from latest to earliest, the + * cursor for the next page can be found as the row with the minimum (earliest) value of + * the tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an + * overview of paginating fetch queries. + */ + fun maxRootSpanId(maxRootSpanId: String?) = + maxRootSpanId(JsonField.ofNullable(maxRootSpanId)) - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ + fun maxRootSpanId(maxRootSpanId: Optional) = + maxRootSpanId(maxRootSpanId.getOrNull()) - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** + * Sets [Builder.maxRootSpanId] to an arbitrary JSON value. + * + * You should usually call [Builder.maxRootSpanId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxRootSpanId(maxRootSpanId: JsonField) = apply { + this.maxRootSpanId = maxRootSpanId + } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + /** + * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor + * of the explicit 'cursor' returned by object fetch requests. Please prefer the + * 'cursor' argument going forwards. + * + * Together, `max_xact_id` and `max_root_span_id` form a pagination cursor + * + * Since a paginated fetch query returns results in order from latest to earliest, the + * cursor for the next page can be found as the row with the minimum (earliest) value of + * the tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an + * overview of paginating fetch queries. + */ + fun maxXactId(maxXactId: String?) = maxXactId(JsonField.ofNullable(maxXactId)) - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ + fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + /** + * Sets [Builder.maxXactId] to an arbitrary JSON value. + * + * You should usually call [Builder.maxXactId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxXactId(maxXactId: JsonField) = apply { this.maxXactId = maxXactId } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + /** + * Retrieve a snapshot of events from a past time + * + * The version id is essentially a filter on the latest event transaction id. You can + * use the `max_xact_id` returned by a past fetch as the version to reproduce that exact + * fetch. + */ + fun version(version: String?) = version(JsonField.ofNullable(version)) + + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) + + /** + * Sets [Builder.version] to an arbitrary JSON value. + * + * You should usually call [Builder.version] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun version(version: JsonField) = apply { this.version = version } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body( + cursor, + limit, + maxRootSpanId, + maxXactId, + version, + additionalProperties.toMutableMap(), + ) + } - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + cursor() + limit() + maxRootSpanId() + maxXactId() + version() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + /** - * Returns an immutable instance of [DatasetFetchPostParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * The following fields are required: - * ```java - * .datasetId() - * ``` - * - * @throws IllegalStateException if any required field is unset. + * Used for best match union deserialization. */ - fun build(): DatasetFetchPostParams = - DatasetFetchPostParams( - checkRequired("datasetId", datasetId), - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + @JvmSynthetic + internal fun validity(): Int = + (if (cursor.asKnown().isPresent) 1 else 0) + + (if (limit.asKnown().isPresent) 1 else 0) + + (if (maxRootSpanId.asKnown().isPresent) 1 else 0) + + (if (maxXactId.asKnown().isPresent) 1 else 0) + + (if (version.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && cursor == other.cursor && limit == other.limit && maxRootSpanId == other.maxRootSpanId && maxXactId == other.maxXactId && version == other.version && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(cursor, limit, maxRootSpanId, maxXactId, version, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{cursor=$cursor, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetInsertParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetInsertParams.kt index 8ed1370b..9156ab3c 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetInsertParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetInsertParams.kt @@ -6,20 +6,20 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 kotlin.jvm.optionals.getOrNull /** Insert a set of events into the dataset */ class DatasetInsertParams @@ -54,170 +54,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> datasetId - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("events") - @ExcludeMissing - private val events: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * A list of dataset events to insert - * - * @throws BraintrustInvalidDataException 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 events(): List = events.getRequired("events") - - /** - * Returns the raw JSON value of [events]. - * - * Unlike [events], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("events") - @ExcludeMissing - fun _events(): JsonField> = events - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - events().forEach { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .events() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var events: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - events = body.events.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** A list of dataset events to insert */ - fun events(events: List) = events(JsonField.of(events)) - - /** - * Sets [Builder.events] to an arbitrary JSON value. - * - * You should usually call [Builder.events] with a well-typed `List` - * value instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun events(events: JsonField>) = apply { - this.events = events.map { it.toMutableList() } - } - - /** - * Adds a single [InsertDatasetEvent] to [events]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addEvent(event: InsertDatasetEvent) = apply { - events = - (events ?: JsonField.of(mutableListOf())).also { - checkKnown("events", it).add(event) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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 - * .events() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("events", events).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && events == other.events && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(events, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Body{events=$events, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -235,7 +71,6 @@ private constructor( } /** A builder for [DatasetInsertParams]. */ - @NoAutoDetect class Builder internal constructor() { private var datasetId: String? = null @@ -254,6 +89,15 @@ private constructor( /** Dataset id */ fun datasetId(datasetId: String) = apply { this.datasetId = datasetId } + /** + * 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: + * - [events] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** A list of dataset events to insert */ fun events(events: List) = apply { body.events(events) } @@ -412,6 +256,195 @@ private constructor( ) } + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> datasetId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val events: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("events") + @ExcludeMissing + events: JsonField> = JsonMissing.of() + ) : this(events, mutableMapOf()) + + /** + * A list of dataset events to insert + * + * @throws BraintrustInvalidDataException 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 events(): List = events.getRequired("events") + + /** + * Returns the raw JSON value of [events]. + * + * Unlike [events], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("events") + @ExcludeMissing + fun _events(): JsonField> = events + + @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 + * .events() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var events: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + events = body.events.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** A list of dataset events to insert */ + fun events(events: List) = events(JsonField.of(events)) + + /** + * Sets [Builder.events] to an arbitrary JSON value. + * + * You should usually call [Builder.events] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun events(events: JsonField>) = apply { + this.events = events.map { it.toMutableList() } + } + + /** + * Adds a single [InsertDatasetEvent] to [events]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addEvent(event: InsertDatasetEvent) = apply { + events = + (events ?: JsonField.of(mutableListOf())).also { + checkKnown("events", it).add(event) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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 + * .events() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("events", events).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + events().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (events.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && events == other.events && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(events, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = "Body{events=$events, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListPage.kt index 51260d7d..9e96f20b 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListPage.kt @@ -2,167 +2,115 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.DatasetService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all datasets. The datasets are sorted by creation date, with the most recently-created - * datasets coming first - */ +/** @see [DatasetService.list] */ class DatasetListPage private constructor( - private val datasetsService: DatasetService, + private val service: DatasetService, private val params: DatasetListParams, - private val response: Response, + private val response: DatasetListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [DatasetListPageResponse], but gracefully handles missing data. + * + * @see [DatasetListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is DatasetListPage && datasetsService == other.datasetsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(datasetsService, params, response) /* spotless:on */ - - override fun toString() = - "DatasetListPage{datasetsService=$datasetsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - DatasetListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - DatasetListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { datasetsService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(datasetsService: DatasetService, params: DatasetListParams, response: Response) = - DatasetListPage(datasetsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): DatasetListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): DatasetListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [DatasetListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [DatasetListPage]. */ + class Builder internal constructor() { - companion object { + private var service: DatasetService? = null + private var params: DatasetListParams? = null + private var response: DatasetListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [DatasetListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(datasetListPage: DatasetListPage) = apply { + service = datasetListPage.service + params = datasetListPage.params + response = datasetListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: DatasetService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: DatasetListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: DatasetListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [DatasetListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): DatasetListPage = + DatasetListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: DatasetListPage) : Iterable { @@ -183,4 +131,17 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is DatasetListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "DatasetListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListPageAsync.kt index 7e0a0e47..c7e230c8 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListPageAsync.kt @@ -2,172 +2,119 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.DatasetServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all datasets. The datasets are sorted by creation date, with the most recently-created - * datasets coming first - */ +/** @see [DatasetServiceAsync.list] */ class DatasetListPageAsync private constructor( - private val datasetsService: DatasetServiceAsync, + private val service: DatasetServiceAsync, private val params: DatasetListParams, - private val response: Response, + private val response: DatasetListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [DatasetListPageResponse], but gracefully handles missing data. + * + * @see [DatasetListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is DatasetListPageAsync && datasetsService == other.datasetsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(datasetsService, params, response) /* spotless:on */ - - override fun toString() = - "DatasetListPageAsync{datasetsService=$datasetsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - DatasetListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - DatasetListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { datasetsService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of( - datasetsService: DatasetServiceAsync, - params: DatasetListParams, - response: Response, - ) = DatasetListPageAsync(datasetsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): DatasetListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): DatasetListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [DatasetListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [DatasetListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: DatasetServiceAsync? = null + private var params: DatasetListParams? = null + private var response: DatasetListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [DatasetListPageAsync]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(datasetListPageAsync: DatasetListPageAsync) = apply { + service = datasetListPageAsync.service + params = datasetListPageAsync.params + response = datasetListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: DatasetServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: DatasetListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: DatasetListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [DatasetListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): DatasetListPageAsync = + DatasetListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: DatasetListPageAsync) { @@ -195,4 +142,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is DatasetListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "DatasetListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListPageResponse.kt new file mode 100644 index 00000000..303e25f0 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListPageResponse.kt @@ -0,0 +1,194 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class DatasetListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") + @ExcludeMissing + objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of dataset objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [DatasetListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [DatasetListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(datasetListPageResponse: DatasetListPageResponse) = apply { + objects = datasetListPageResponse.objects.map { it.toMutableList() } + additionalProperties = datasetListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of dataset objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [Dataset] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: Dataset) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [DatasetListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): DatasetListPageResponse = + DatasetListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): DatasetListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is DatasetListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "DatasetListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListParams.kt index 90416929..5928e94b 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListParams.kt @@ -2,22 +2,10 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -83,33 +71,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - datasetName?.let { put("dataset_name", it) } - endingBefore?.let { put("ending_before", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - orgName?.let { put("org_name", it) } - projectId?.let { put("project_id", it) } - projectName?.let { put("project_name", it) } - startingAfter?.let { put("starting_after", it) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -121,7 +82,6 @@ private constructor( } /** A builder for [DatasetListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var datasetName: String? = null @@ -344,17 +304,41 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + datasetName?.let { put("dataset_name", it) } + endingBefore?.let { put("ending_before", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + orgName?.let { put("org_name", it) } + projectId?.let { put("project_id", it) } + projectName?.let { put("project_name", it) } + startingAfter?.let { put("starting_after", it) } + putAll(additionalQueryParams) + } + .build() + /** * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -369,15 +353,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -393,7 +374,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -410,51 +390,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetRetrieveParams.kt index ef2657ae..27bc2e38 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> datasetId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [DatasetRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var datasetId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> datasetId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetSummarizeParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetSummarizeParams.kt index d188b51b..998d598b 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetSummarizeParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetSummarizeParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -30,23 +29,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - summarizeData?.let { put("summarize_data", it.toString()) } - putAll(additionalQueryParams) - } - .build() - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> datasetId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -63,7 +45,6 @@ private constructor( } /** A builder for [DatasetSummarizeParams]. */ - @NoAutoDetect class Builder internal constructor() { private var datasetId: String? = null @@ -217,6 +198,22 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> datasetId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + summarizeData?.let { put("summarize_data", it.toString()) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetUpdateParams.kt index 038dc497..53ef6810 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetUpdateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetUpdateParams.kt @@ -6,18 +6,17 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -89,218 +88,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> datasetId - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * Textual description of the dataset - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - /** - * User-controlled metadata about the dataset - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) - - /** - * Name of the dataset. Within a project, dataset names are unique - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** - * Returns the raw JSON value of [description]. - * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description - - /** - * Returns the raw JSON value of [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 [name]. - * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - description() - metadata().ifPresent { it.validate() } - name() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Body]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var description: JsonField = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - description = body.description - metadata = body.metadata - name = body.name - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** Textual description of the dataset */ - fun description(description: String?) = description(JsonField.ofNullable(description)) - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } - - /** User-controlled metadata about the dataset */ - 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 } - - /** Name of the dataset. Within a project, dataset names are unique */ - 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 additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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. - */ - fun build(): Body = - Body(description, metadata, name, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && description == other.description && metadata == other.metadata && name == other.name && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(description, metadata, name, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{description=$description, metadata=$metadata, name=$name, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -317,7 +104,6 @@ private constructor( } /** A builder for [DatasetUpdateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var datasetId: String? = null @@ -336,6 +122,17 @@ private constructor( /** Dataset id */ fun datasetId(datasetId: String) = apply { this.datasetId = datasetId } + /** + * 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: + * - [description] + * - [metadata] + * - [name] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** Textual description of the dataset */ fun description(description: String?) = apply { body.description(description) } @@ -518,29 +315,256 @@ private constructor( ) } - /** User-controlled metadata about the dataset */ - @NoAutoDetect - class Metadata - @JsonCreator + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> datasetId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + private val description: JsonField, + private val metadata: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(description, metadata, name, mutableMapOf()) + + /** + * Textual description of the dataset + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * User-controlled metadata about the dataset + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * Name of the dataset. Within a project, dataset names are unique + * + * @throws BraintrustInvalidDataException 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 [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [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 [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 = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var description: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + description = body.description + metadata = body.metadata + name = body.name + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Textual description of the dataset */ + fun description(description: String?) = description(JsonField.ofNullable(description)) + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + + /** User-controlled metadata about the dataset */ + 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 } + + /** Name of the dataset. Within a project, dataset names are unique */ + 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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. + */ + fun build(): Body = + Body(description, metadata, name, additionalProperties.toMutableMap()) + } private var validated: Boolean = false - fun validate(): Metadata = apply { + fun validate(): Body = apply { if (validated) { return@apply } + description() + metadata().ifPresent { it.validate() } + name() validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (description.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && description == other.description && metadata == other.metadata && name == other.name && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(description, metadata, name, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{description=$description, metadata=$metadata, name=$name, additionalProperties=$additionalProperties}" + } + + /** User-controlled metadata about the dataset */ + 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 { @@ -586,6 +610,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVar.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVar.kt index 739d7149..6eed845c 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVar.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVar.kt @@ -7,41 +7,43 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class EnvVar -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("used") - @ExcludeMissing - private val used: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val name: JsonField, + private val objectId: JsonField, + private val objectType: JsonField, + private val created: JsonField, + private val used: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("object_id") @ExcludeMissing objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("used") @ExcludeMissing used: JsonField = JsonMissing.of(), + ) : this(id, name, objectId, objectType, created, used, mutableMapOf()) + /** * Unique identifier for the environment variable * @@ -80,7 +82,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Date the environment variable was last used @@ -88,7 +90,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun used(): Optional = Optional.ofNullable(used.getNullable("used")) + fun used(): Optional = used.getOptional("used") /** * Returns the raw JSON value of [id]. @@ -134,25 +136,15 @@ private constructor( */ @JsonProperty("used") @ExcludeMissing fun _used(): JsonField = used + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): EnvVar = apply { - if (validated) { - return@apply - } - - id() - name() - objectId() - objectType() - created() - used() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -311,10 +303,48 @@ private constructor( checkRequired("objectType", objectType), created, used, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): EnvVar = apply { + if (validated) { + return@apply + } + + id() + name() + objectId() + objectType().validate() + created() + used() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (used.asKnown().isPresent) 1 else 0) + /** The type of the object the environment variable is scoped for */ class ObjectType @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -411,6 +441,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ObjectType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarCreateParams.kt index ba236659..95f3d594 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarCreateParams.kt @@ -7,18 +7,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -100,32 +98,263 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [EnvVarCreateParams]. + * + * The following fields are required: + * ```java + * .name() + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [EnvVarCreateParams]. */ + 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(envVarCreateParams: EnvVarCreateParams) = apply { + body = envVarCreateParams.body.toBuilder() + additionalHeaders = envVarCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = envVarCreateParams.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: + * - [name] + * - [objectId] + * - [objectType] + * - [value] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** The name of the environment variable */ + fun name(name: String) = apply { body.name(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 { body.name(name) } + + /** The id of the object the environment variable is scoped for */ + fun objectId(objectId: String) = apply { body.objectId(objectId) } + + /** + * Sets [Builder.objectId] to an arbitrary JSON value. + * + * You should usually call [Builder.objectId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun objectId(objectId: JsonField) = apply { body.objectId(objectId) } + + /** The type of the object the environment variable is scoped for */ + fun objectType(objectType: ObjectType) = apply { body.objectType(objectType) } + + /** + * Sets [Builder.objectType] to an arbitrary JSON value. + * + * You should usually call [Builder.objectType] with a well-typed [ObjectType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectType(objectType: JsonField) = apply { body.objectType(objectType) } + + /** The value of the environment variable. Will be encrypted at rest. */ + fun value(value: String?) = apply { body.value(value) } + + /** Alias for calling [Builder.value] with `value.orElse(null)`. */ + fun value(value: Optional) = value(value.getOrNull()) + + /** + * Sets [Builder.value] to an arbitrary JSON value. + * + * You should usually call [Builder.value] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun value(value: JsonField) = apply { body.value(value) } + + 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 [EnvVarCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .objectId() + * .objectType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): EnvVarCreateParams = + EnvVarCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body override fun _headers(): Headers = additionalHeaders override fun _queryParams(): QueryParams = additionalQueryParams - @NoAutoDetect class Body - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("value") - @ExcludeMissing - private val value: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val objectId: JsonField, + private val objectType: JsonField, + private val value: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("object_id") + @ExcludeMissing + objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonField = JsonMissing.of(), + ) : this(name, objectId, objectType, value, mutableMapOf()) + /** * The name of the environment variable * @@ -156,7 +385,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun value(): Optional = Optional.ofNullable(value.getNullable("value")) + fun value(): Optional = value.getOptional("value") /** * Returns the raw JSON value of [name]. @@ -188,23 +417,15 @@ private constructor( */ @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - name() - objectId() - objectType() - value() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -333,245 +554,61 @@ private constructor( checkRequired("objectId", objectId), checkRequired("objectType", objectType), value, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply } - return /* spotless:off */ other is Body && name == other.name && objectId == other.objectId && objectType == other.objectType && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ + name() + objectId() + objectType().validate() + value() + validated = true } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, objectId, objectType, value, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{name=$name, objectId=$objectId, objectType=$objectType, value=$value, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } /** - * Returns a mutable builder for constructing an instance of [EnvVarCreateParams]. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * The following fields are required: - * ```java - * .name() - * .objectId() - * .objectType() - * ``` + * Used for best match union deserialization. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [EnvVarCreateParams]. */ - @NoAutoDetect - 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(envVarCreateParams: EnvVarCreateParams) = apply { - body = envVarCreateParams.body.toBuilder() - additionalHeaders = envVarCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = envVarCreateParams.additionalQueryParams.toBuilder() - } - - /** The name of the environment variable */ - fun name(name: String) = apply { body.name(name) } + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (value.asKnown().isPresent) 1 else 0) - /** - * 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 { body.name(name) } - - /** The id of the object the environment variable is scoped for */ - fun objectId(objectId: String) = apply { body.objectId(objectId) } - - /** - * Sets [Builder.objectId] to an arbitrary JSON value. - * - * You should usually call [Builder.objectId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun objectId(objectId: JsonField) = apply { body.objectId(objectId) } - - /** The type of the object the environment variable is scoped for */ - fun objectType(objectType: ObjectType) = apply { body.objectType(objectType) } - - /** - * Sets [Builder.objectType] to an arbitrary JSON value. - * - * You should usually call [Builder.objectType] with a well-typed [ObjectType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun objectType(objectType: JsonField) = apply { body.objectType(objectType) } - - /** The value of the environment variable. Will be encrypted at rest. */ - fun value(value: String?) = apply { body.value(value) } - - /** Alias for calling [Builder.value] with `value.orElse(null)`. */ - fun value(value: Optional) = value(value.getOrNull()) - - /** - * Sets [Builder.value] to an arbitrary JSON value. - * - * You should usually call [Builder.value] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun value(value: JsonField) = apply { body.value(value) } - - 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) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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) + return /* spotless:off */ other is Body && name == other.name && objectId == other.objectId && objectType == other.objectType && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, objectId, objectType, value, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [EnvVarCreateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .objectId() - * .objectType() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): EnvVarCreateParams = - EnvVarCreateParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{name=$name, objectId=$objectId, objectType=$objectType, value=$value, additionalProperties=$additionalProperties}" } /** The type of the object the environment variable is scoped for */ @@ -670,6 +707,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ObjectType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarDeleteParams.kt index 8675b2e0..9547d21a 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarDeleteParams.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,26 +23,11 @@ private constructor( /** EnvVar id */ fun envVarId(): String = envVarId - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> envVarId - else -> "" - } - } + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -61,7 +45,6 @@ private constructor( } /** A builder for [EnvVarDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var envVarId: String? = null @@ -221,6 +204,19 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> envVarId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarListParams.kt index 4977d934..420b7e23 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarListParams.kt @@ -2,22 +2,10 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -59,30 +47,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - envVarName?.let { put("env_var_name", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - objectId?.let { put("object_id", it) } - objectType?.let { put("object_type", it.asString()) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -94,7 +58,6 @@ private constructor( } /** A builder for [EnvVarListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var envVarName: String? = null @@ -277,17 +240,38 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + envVarName?.let { put("env_var_name", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + objectId?.let { put("object_id", it) } + objectType?.let { put("object_type", it.toString()) } + putAll(additionalQueryParams) + } + .build() + /** * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -302,15 +286,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -326,7 +307,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -343,51 +323,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarListResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarListResponse.kt index dc10c986..5b96d587 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarListResponse.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarListResponse.kt @@ -6,28 +6,29 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 kotlin.jvm.optionals.getOrNull -@NoAutoDetect class EnvVarListResponse -@JsonCreator private constructor( - @JsonProperty("objects") - @ExcludeMissing - private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val objects: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("objects") @ExcludeMissing objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + /** * A list of env_var objects * @@ -43,20 +44,15 @@ private constructor( */ @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): EnvVarListResponse = apply { - if (validated) { - return@apply - } - - objects().forEach { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -145,10 +141,38 @@ private constructor( fun build(): EnvVarListResponse = EnvVarListResponse( checkRequired("objects", objects).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): EnvVarListResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarObjectType.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarObjectType.kt index b78e5292..db76bd2a 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarObjectType.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarObjectType.kt @@ -101,6 +101,32 @@ class EnvVarObjectType @JsonCreator private constructor(private val value: JsonF fun asString(): String = _value().asString().orElseThrow { BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): EnvVarObjectType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarReplaceParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarReplaceParams.kt index 4c9da803..10e7bda1 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarReplaceParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarReplaceParams.kt @@ -7,18 +7,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -100,32 +98,263 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [EnvVarReplaceParams]. + * + * The following fields are required: + * ```java + * .name() + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [EnvVarReplaceParams]. */ + 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(envVarReplaceParams: EnvVarReplaceParams) = apply { + body = envVarReplaceParams.body.toBuilder() + additionalHeaders = envVarReplaceParams.additionalHeaders.toBuilder() + additionalQueryParams = envVarReplaceParams.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: + * - [name] + * - [objectId] + * - [objectType] + * - [value] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** The name of the environment variable */ + fun name(name: String) = apply { body.name(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 { body.name(name) } + + /** The id of the object the environment variable is scoped for */ + fun objectId(objectId: String) = apply { body.objectId(objectId) } + + /** + * Sets [Builder.objectId] to an arbitrary JSON value. + * + * You should usually call [Builder.objectId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun objectId(objectId: JsonField) = apply { body.objectId(objectId) } + + /** The type of the object the environment variable is scoped for */ + fun objectType(objectType: ObjectType) = apply { body.objectType(objectType) } + + /** + * Sets [Builder.objectType] to an arbitrary JSON value. + * + * You should usually call [Builder.objectType] with a well-typed [ObjectType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectType(objectType: JsonField) = apply { body.objectType(objectType) } + + /** The value of the environment variable. Will be encrypted at rest. */ + fun value(value: String?) = apply { body.value(value) } + + /** Alias for calling [Builder.value] with `value.orElse(null)`. */ + fun value(value: Optional) = value(value.getOrNull()) + + /** + * Sets [Builder.value] to an arbitrary JSON value. + * + * You should usually call [Builder.value] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun value(value: JsonField) = apply { body.value(value) } + + 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 [EnvVarReplaceParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .objectId() + * .objectType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): EnvVarReplaceParams = + EnvVarReplaceParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body override fun _headers(): Headers = additionalHeaders override fun _queryParams(): QueryParams = additionalQueryParams - @NoAutoDetect class Body - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("value") - @ExcludeMissing - private val value: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val objectId: JsonField, + private val objectType: JsonField, + private val value: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("object_id") + @ExcludeMissing + objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonField = JsonMissing.of(), + ) : this(name, objectId, objectType, value, mutableMapOf()) + /** * The name of the environment variable * @@ -156,7 +385,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun value(): Optional = Optional.ofNullable(value.getNullable("value")) + fun value(): Optional = value.getOptional("value") /** * Returns the raw JSON value of [name]. @@ -188,23 +417,15 @@ private constructor( */ @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - name() - objectId() - objectType() - value() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -333,245 +554,61 @@ private constructor( checkRequired("objectId", objectId), checkRequired("objectType", objectType), value, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply } - return /* spotless:off */ other is Body && name == other.name && objectId == other.objectId && objectType == other.objectType && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ + name() + objectId() + objectType().validate() + value() + validated = true } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, objectId, objectType, value, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{name=$name, objectId=$objectId, objectType=$objectType, value=$value, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } /** - * Returns a mutable builder for constructing an instance of [EnvVarReplaceParams]. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * The following fields are required: - * ```java - * .name() - * .objectId() - * .objectType() - * ``` + * Used for best match union deserialization. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [EnvVarReplaceParams]. */ - @NoAutoDetect - 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(envVarReplaceParams: EnvVarReplaceParams) = apply { - body = envVarReplaceParams.body.toBuilder() - additionalHeaders = envVarReplaceParams.additionalHeaders.toBuilder() - additionalQueryParams = envVarReplaceParams.additionalQueryParams.toBuilder() - } - - /** The name of the environment variable */ - fun name(name: String) = apply { body.name(name) } + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (value.asKnown().isPresent) 1 else 0) - /** - * 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 { body.name(name) } - - /** The id of the object the environment variable is scoped for */ - fun objectId(objectId: String) = apply { body.objectId(objectId) } - - /** - * Sets [Builder.objectId] to an arbitrary JSON value. - * - * You should usually call [Builder.objectId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun objectId(objectId: JsonField) = apply { body.objectId(objectId) } - - /** The type of the object the environment variable is scoped for */ - fun objectType(objectType: ObjectType) = apply { body.objectType(objectType) } - - /** - * Sets [Builder.objectType] to an arbitrary JSON value. - * - * You should usually call [Builder.objectType] with a well-typed [ObjectType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun objectType(objectType: JsonField) = apply { body.objectType(objectType) } - - /** The value of the environment variable. Will be encrypted at rest. */ - fun value(value: String?) = apply { body.value(value) } - - /** Alias for calling [Builder.value] with `value.orElse(null)`. */ - fun value(value: Optional) = value(value.getOrNull()) - - /** - * Sets [Builder.value] to an arbitrary JSON value. - * - * You should usually call [Builder.value] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun value(value: JsonField) = apply { body.value(value) } - - 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) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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) + return /* spotless:off */ other is Body && name == other.name && objectId == other.objectId && objectType == other.objectType && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, objectId, objectType, value, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [EnvVarReplaceParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .objectId() - * .objectType() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): EnvVarReplaceParams = - EnvVarReplaceParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{name=$name, objectId=$objectId, objectType=$objectType, value=$value, additionalProperties=$additionalProperties}" } /** The type of the object the environment variable is scoped for */ @@ -670,6 +707,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ObjectType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarRetrieveParams.kt index 588b7b7c..00b5ca97 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> envVarId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [EnvVarRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var envVarId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> envVarId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarUpdateParams.kt index 58ba35d3..0283dad1 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarUpdateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarUpdateParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -74,188 +72,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> envVarId - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("value") - @ExcludeMissing - private val value: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * The name of the environment variable - * - * @throws BraintrustInvalidDataException 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") - - /** - * The value of the environment variable. Will be encrypted at rest. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun value(): Optional = Optional.ofNullable(value.getNullable("value")) - - /** - * 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 [value]. - * - * Unlike [value], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - name() - value() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var name: JsonField? = null - private var value: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - value = body.value - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** The name of the environment variable */ - fun name(name: String) = name(JsonField.of(name)) - - /** - * Sets [Builder.name] to an arbitrary JSON value. - * - * You should usually call [Builder.name] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun name(name: JsonField) = apply { this.name = name } - - /** The value of the environment variable. Will be encrypted at rest. */ - fun value(value: String?) = value(JsonField.ofNullable(value)) - - /** Alias for calling [Builder.value] with `value.orElse(null)`. */ - fun value(value: Optional) = value(value.getOrNull()) - - /** - * Sets [Builder.value] to an arbitrary JSON value. - * - * You should usually call [Builder.value] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun value(value: JsonField) = apply { this.value = 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 [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body(checkRequired("name", name), value, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && name == other.name && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, value, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{name=$name, value=$value, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -273,7 +89,6 @@ private constructor( } /** A builder for [EnvVarUpdateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var envVarId: String? = null @@ -292,6 +107,16 @@ private constructor( /** EnvVar id */ fun envVarId(envVarId: String) = apply { this.envVarId = envVarId } + /** + * 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: + * - [name] + * - [value] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** The name of the environment variable */ fun name(name: String) = apply { body.name(name) } @@ -456,6 +281,210 @@ private constructor( ) } + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> envVarId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val name: JsonField, + private val value: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonField = JsonMissing.of(), + ) : this(name, value, mutableMapOf()) + + /** + * The name of the environment variable + * + * @throws BraintrustInvalidDataException 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") + + /** + * The value of the environment variable. Will be encrypted at rest. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun value(): Optional = value.getOptional("value") + + /** + * 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 [value]. + * + * Unlike [value], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value + + @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 + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var value: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + value = body.value + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** The name of the environment variable */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** The value of the environment variable. Will be encrypted at rest. */ + fun value(value: String?) = value(JsonField.ofNullable(value)) + + /** Alias for calling [Builder.value] with `value.orElse(null)`. */ + fun value(value: Optional) = value(value.getOrNull()) + + /** + * Sets [Builder.value] to an arbitrary JSON value. + * + * You should usually call [Builder.value] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun value(value: JsonField) = apply { this.value = 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 [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body(checkRequired("name", name), value, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + (if (value.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && name == other.name && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, value, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, value=$value, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EvalCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EvalCreateParams.kt index 96d00635..0583e3ba 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EvalCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EvalCreateParams.kt @@ -9,14 +9,13 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.allMaxBy import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -30,6 +29,7 @@ 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.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -308,1398 +308,1476 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun toBuilder() = Builder().from(this) - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("data") @ExcludeMissing private val data: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("scores") - @ExcludeMissing - private val scores: JsonField> = JsonMissing.of(), - @JsonProperty("task") @ExcludeMissing private val task: JsonField = JsonMissing.of(), - @JsonProperty("base_experiment_id") - @ExcludeMissing - private val baseExperimentId: JsonField = JsonMissing.of(), - @JsonProperty("base_experiment_name") - @ExcludeMissing - private val baseExperimentName: JsonField = JsonMissing.of(), - @JsonProperty("experiment_name") - @ExcludeMissing - private val experimentName: JsonField = JsonMissing.of(), - @JsonProperty("git_metadata_settings") - @ExcludeMissing - private val gitMetadataSettings: JsonField = JsonMissing.of(), - @JsonProperty("is_public") - @ExcludeMissing - private val isPublic: JsonField = JsonMissing.of(), - @JsonProperty("max_concurrency") - @ExcludeMissing - private val maxConcurrency: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("parent") - @ExcludeMissing - private val parent: JsonField = JsonMissing.of(), - @JsonProperty("repo_info") - @ExcludeMissing - private val repoInfo: JsonField = JsonMissing.of(), - @JsonProperty("stream") - @ExcludeMissing - private val stream: JsonField = JsonMissing.of(), - @JsonProperty("timeout") - @ExcludeMissing - private val timeout: JsonField = JsonMissing.of(), - @JsonProperty("trial_count") - @ExcludeMissing - private val trialCount: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + companion object { /** - * The dataset to use + * Returns a mutable builder for constructing an instance of [EvalCreateParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .data() + * .projectId() + * .scores() + * .task() + * ``` */ - fun data(): Data = data.getRequired("data") + @JvmStatic fun builder() = Builder() + } - /** - * Unique identifier for the project to run the eval in - * - * @throws BraintrustInvalidDataException 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 projectId(): String = projectId.getRequired("project_id") + /** A builder for [EvalCreateParams]. */ + 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(evalCreateParams: EvalCreateParams) = apply { + body = evalCreateParams.body.toBuilder() + additionalHeaders = evalCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = evalCreateParams.additionalQueryParams.toBuilder() + } /** - * The functions to score the eval on + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * 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: + * - [data] + * - [projectId] + * - [scores] + * - [task] + * - [baseExperimentId] + * - etc. */ - fun scores(): List = scores.getRequired("scores") + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** The dataset to use */ + fun data(data: Data) = apply { body.data(data) } /** - * The function to evaluate + * Sets [Builder.data] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - fun task(): Task = task.getRequired("task") + fun data(data: JsonField) = apply { body.data(data) } + + /** Alias for calling [data] with `Data.ofDatasetId(datasetId)`. */ + fun data(datasetId: Data.DatasetId) = apply { body.data(datasetId) } + + /** Alias for calling [data] with `Data.ofProjectDatasetName(projectDatasetName)`. */ + fun data(projectDatasetName: Data.ProjectDatasetName) = apply { + body.data(projectDatasetName) + } + + /** Alias for calling [data] with `Data.ofDatasetRows(datasetRows)`. */ + fun data(datasetRows: Data.DatasetRows) = apply { body.data(datasetRows) } + + /** Unique identifier for the project to run the eval in */ + fun projectId(projectId: String) = apply { body.projectId(projectId) } /** - * An optional experiment id to use as a base. If specified, the new experiment will be - * summarized and compared to this experiment. + * Sets [Builder.projectId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun baseExperimentId(): Optional = - Optional.ofNullable(baseExperimentId.getNullable("base_experiment_id")) + fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } + + /** The functions to score the eval on */ + fun scores(scores: List) = apply { body.scores(scores) } /** - * An optional experiment name to use as a base. If specified, the new experiment will be - * summarized and compared to this experiment. + * Sets [Builder.scores] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.scores] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun baseExperimentName(): Optional = - Optional.ofNullable(baseExperimentName.getNullable("base_experiment_name")) + fun scores(scores: JsonField>) = apply { body.scores(scores) } /** - * An optional name for the experiment created by this eval. If it conflicts with an - * existing experiment, it will be suffixed with a unique identifier. + * Adds a single [Score] to [scores]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * @throws IllegalStateException if the field was previously set to a non-list. */ - fun experimentName(): Optional = - Optional.ofNullable(experimentName.getNullable("experiment_name")) + fun addScore(score: Score) = apply { body.addScore(score) } + + /** Alias for calling [addScore] with `Score.ofFunctionId(functionId)`. */ + fun addScore(functionId: Score.FunctionId) = apply { body.addScore(functionId) } + + /** Alias for calling [addScore] with `Score.ofProjectSlug(projectSlug)`. */ + fun addScore(projectSlug: Score.ProjectSlug) = apply { body.addScore(projectSlug) } + + /** Alias for calling [addScore] with `Score.ofGlobalFunction(globalFunction)`. */ + fun addScore(globalFunction: Score.GlobalFunction) = apply { body.addScore(globalFunction) } + + /** Alias for calling [addScore] with `Score.ofPromptSessionId(promptSessionId)`. */ + fun addScore(promptSessionId: Score.PromptSessionId) = apply { + body.addScore(promptSessionId) + } + + /** Alias for calling [addScore] with `Score.ofInlineCode(inlineCode)`. */ + fun addScore(inlineCode: Score.InlineCode) = apply { body.addScore(inlineCode) } + + /** Alias for calling [addScore] with `Score.ofInlinePrompt(inlinePrompt)`. */ + fun addScore(inlinePrompt: Score.InlinePrompt) = apply { body.addScore(inlinePrompt) } + + /** The function to evaluate */ + fun task(task: Task) = apply { body.task(task) } /** - * Optional settings for collecting git metadata. By default, will collect all git metadata - * fields allowed in org-level settings. + * Sets [Builder.task] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.task] with a well-typed [Task] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - fun gitMetadataSettings(): Optional = - Optional.ofNullable(gitMetadataSettings.getNullable("git_metadata_settings")) + fun task(task: JsonField) = apply { body.task(task) } + + /** Alias for calling [task] with `Task.ofFunctionId(functionId)`. */ + fun task(functionId: Task.FunctionId) = apply { body.task(functionId) } + + /** Alias for calling [task] with `Task.ofProjectSlug(projectSlug)`. */ + fun task(projectSlug: Task.ProjectSlug) = apply { body.task(projectSlug) } + + /** Alias for calling [task] with `Task.ofGlobalFunction(globalFunction)`. */ + fun task(globalFunction: Task.GlobalFunction) = apply { body.task(globalFunction) } + + /** Alias for calling [task] with `Task.ofPromptSessionId(promptSessionId)`. */ + fun task(promptSessionId: Task.PromptSessionId) = apply { body.task(promptSessionId) } + + /** Alias for calling [task] with `Task.ofInlineCode(inlineCode)`. */ + fun task(inlineCode: Task.InlineCode) = apply { body.task(inlineCode) } + + /** Alias for calling [task] with `Task.ofInlinePrompt(inlinePrompt)`. */ + fun task(inlinePrompt: Task.InlinePrompt) = apply { body.task(inlinePrompt) } /** - * Whether the experiment should be public. Defaults to false. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * An optional experiment id to use as a base. If specified, the new experiment will be + * summarized and compared to this experiment. */ - fun isPublic(): Optional = Optional.ofNullable(isPublic.getNullable("is_public")) + fun baseExperimentId(baseExperimentId: String?) = apply { + body.baseExperimentId(baseExperimentId) + } + + /** Alias for calling [Builder.baseExperimentId] with `baseExperimentId.orElse(null)`. */ + fun baseExperimentId(baseExperimentId: Optional) = + baseExperimentId(baseExperimentId.getOrNull()) /** - * The maximum number of tasks/scorers that will be run concurrently. Defaults to undefined, - * in which case there is no max concurrency. + * Sets [Builder.baseExperimentId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.baseExperimentId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun maxConcurrency(): Optional = - Optional.ofNullable(maxConcurrency.getNullable("max_concurrency")) + fun baseExperimentId(baseExperimentId: JsonField) = apply { + body.baseExperimentId(baseExperimentId) + } /** - * Optional experiment-level metadata to store about the evaluation. You can later use this - * to slice & dice across experiments. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * An optional experiment name to use as a base. If specified, the new experiment will be + * summarized and compared to this experiment. */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun baseExperimentName(baseExperimentName: String?) = apply { + body.baseExperimentName(baseExperimentName) + } /** - * Options for tracing the evaluation - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * Alias for calling [Builder.baseExperimentName] with `baseExperimentName.orElse(null)`. */ - fun parent(): Optional = Optional.ofNullable(parent.getNullable("parent")) + fun baseExperimentName(baseExperimentName: Optional) = + baseExperimentName(baseExperimentName.getOrNull()) /** - * Metadata about the state of the repo when the experiment was created + * Sets [Builder.baseExperimentName] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.baseExperimentName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun repoInfo(): Optional = Optional.ofNullable(repoInfo.getNullable("repo_info")) + fun baseExperimentName(baseExperimentName: JsonField) = apply { + body.baseExperimentName(baseExperimentName) + } /** - * Whether to stream the results of the eval. If true, the request will return two events: - * one to indicate the experiment has started, and another upon completion. If false, the - * request will return the evaluation's summary upon completion. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * An optional name for the experiment created by this eval. If it conflicts with an + * existing experiment, it will be suffixed with a unique identifier. */ - fun stream(): Optional = Optional.ofNullable(stream.getNullable("stream")) + fun experimentName(experimentName: String) = apply { body.experimentName(experimentName) } /** - * The maximum duration, in milliseconds, to run the evaluation. Defaults to undefined, in - * which case there is no timeout. + * Sets [Builder.experimentName] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.experimentName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun timeout(): Optional = Optional.ofNullable(timeout.getNullable("timeout")) + fun experimentName(experimentName: JsonField) = apply { + body.experimentName(experimentName) + } /** - * The number of times to run the evaluator per input. This is useful for evaluating - * applications that have non-deterministic behavior and gives you both a stronger aggregate - * measure and a sense of the variance in the results. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * Optional settings for collecting git metadata. By default, will collect all git metadata + * fields allowed in org-level settings. */ - fun trialCount(): Optional = - Optional.ofNullable(trialCount.getNullable("trial_count")) + fun gitMetadataSettings(gitMetadataSettings: GitMetadataSettings?) = apply { + body.gitMetadataSettings(gitMetadataSettings) + } /** - * Returns the raw JSON value of [data]. - * - * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + * Alias for calling [Builder.gitMetadataSettings] with `gitMetadataSettings.orElse(null)`. */ - @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + fun gitMetadataSettings(gitMetadataSettings: Optional) = + gitMetadataSettings(gitMetadataSettings.getOrNull()) /** - * Returns the raw JSON value of [projectId]. + * Sets [Builder.gitMetadataSettings] to an arbitrary JSON value. * - * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.gitMetadataSettings] with a well-typed + * [GitMetadataSettings] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId + fun gitMetadataSettings(gitMetadataSettings: JsonField) = apply { + body.gitMetadataSettings(gitMetadataSettings) + } + + /** Whether the experiment should be public. Defaults to false. */ + fun isPublic(isPublic: Boolean?) = apply { body.isPublic(isPublic) } /** - * Returns the raw JSON value of [scores]. + * Alias for [Builder.isPublic]. * - * Unlike [scores], this method doesn't throw if the JSON field has an unexpected type. + * This unboxed primitive overload exists for backwards compatibility. */ - @JsonProperty("scores") @ExcludeMissing fun _scores(): JsonField> = scores + fun isPublic(isPublic: Boolean) = isPublic(isPublic as Boolean?) + + /** Alias for calling [Builder.isPublic] with `isPublic.orElse(null)`. */ + fun isPublic(isPublic: Optional) = isPublic(isPublic.getOrNull()) /** - * Returns the raw JSON value of [task]. + * Sets [Builder.isPublic] to an arbitrary JSON value. * - * Unlike [task], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.isPublic] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("task") @ExcludeMissing fun _task(): JsonField = task + fun isPublic(isPublic: JsonField) = apply { body.isPublic(isPublic) } /** - * Returns the raw JSON value of [baseExperimentId]. - * - * Unlike [baseExperimentId], this method doesn't throw if the JSON field has an unexpected - * type. + * The maximum number of tasks/scorers that will be run concurrently. Defaults to undefined, + * in which case there is no max concurrency. */ - @JsonProperty("base_experiment_id") - @ExcludeMissing - fun _baseExperimentId(): JsonField = baseExperimentId + fun maxConcurrency(maxConcurrency: Double?) = apply { body.maxConcurrency(maxConcurrency) } /** - * Returns the raw JSON value of [baseExperimentName]. + * Alias for [Builder.maxConcurrency]. * - * Unlike [baseExperimentName], this method doesn't throw if the JSON field has an - * unexpected type. + * This unboxed primitive overload exists for backwards compatibility. */ - @JsonProperty("base_experiment_name") - @ExcludeMissing - fun _baseExperimentName(): JsonField = baseExperimentName + fun maxConcurrency(maxConcurrency: Double) = maxConcurrency(maxConcurrency as Double?) + + /** Alias for calling [Builder.maxConcurrency] with `maxConcurrency.orElse(null)`. */ + fun maxConcurrency(maxConcurrency: Optional) = + maxConcurrency(maxConcurrency.getOrNull()) /** - * Returns the raw JSON value of [experimentName]. + * Sets [Builder.maxConcurrency] to an arbitrary JSON value. * - * Unlike [experimentName], this method doesn't throw if the JSON field has an unexpected - * type. + * You should usually call [Builder.maxConcurrency] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("experiment_name") - @ExcludeMissing - fun _experimentName(): JsonField = experimentName + fun maxConcurrency(maxConcurrency: JsonField) = apply { + body.maxConcurrency(maxConcurrency) + } /** - * Returns the raw JSON value of [gitMetadataSettings]. - * - * Unlike [gitMetadataSettings], this method doesn't throw if the JSON field has an - * unexpected type. + * Optional experiment-level metadata to store about the evaluation. You can later use this + * to slice & dice across experiments. */ - @JsonProperty("git_metadata_settings") - @ExcludeMissing - fun _gitMetadataSettings(): JsonField = gitMetadataSettings + fun metadata(metadata: Metadata) = apply { body.metadata(metadata) } /** - * Returns the raw JSON value of [isPublic]. + * Sets [Builder.metadata] to an arbitrary JSON value. * - * Unlike [isPublic], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("is_public") @ExcludeMissing fun _isPublic(): JsonField = isPublic + fun metadata(metadata: JsonField) = apply { body.metadata(metadata) } + + /** Options for tracing the evaluation */ + fun parent(parent: Parent) = apply { body.parent(parent) } /** - * Returns the raw JSON value of [maxConcurrency]. + * Sets [Builder.parent] to an arbitrary JSON value. * - * Unlike [maxConcurrency], this method doesn't throw if the JSON field has an unexpected - * type. + * You should usually call [Builder.parent] with a well-typed [Parent] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("max_concurrency") - @ExcludeMissing - fun _maxConcurrency(): JsonField = maxConcurrency + fun parent(parent: JsonField) = apply { body.parent(parent) } + + /** Alias for calling [parent] with `Parent.ofSpanParentStruct(spanParentStruct)`. */ + fun parent(spanParentStruct: Parent.SpanParentStruct) = apply { + body.parent(spanParentStruct) + } + + /** Alias for calling [parent] with `Parent.ofString(string)`. */ + fun parent(string: String) = apply { body.parent(string) } + + /** Metadata about the state of the repo when the experiment was created */ + fun repoInfo(repoInfo: RepoInfo?) = apply { body.repoInfo(repoInfo) } + + /** Alias for calling [Builder.repoInfo] with `repoInfo.orElse(null)`. */ + fun repoInfo(repoInfo: Optional) = repoInfo(repoInfo.getOrNull()) /** - * Returns the raw JSON value of [metadata]. + * Sets [Builder.repoInfo] to an arbitrary JSON value. * - * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.repoInfo] with a well-typed [RepoInfo] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + fun repoInfo(repoInfo: JsonField) = apply { body.repoInfo(repoInfo) } /** - * Returns the raw JSON value of [parent]. + * Whether to stream the results of the eval. If true, the request will return two events: + * one to indicate the experiment has started, and another upon completion. If false, the + * request will return the evaluation's summary upon completion. + */ + fun stream(stream: Boolean) = apply { body.stream(stream) } + + /** + * Sets [Builder.stream] to an arbitrary JSON value. * - * Unlike [parent], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("parent") @ExcludeMissing fun _parent(): JsonField = parent + fun stream(stream: JsonField) = apply { body.stream(stream) } /** - * Returns the raw JSON value of [repoInfo]. + * The maximum duration, in milliseconds, to run the evaluation. Defaults to undefined, in + * which case there is no timeout. + */ + fun timeout(timeout: Double?) = apply { body.timeout(timeout) } + + /** + * Alias for [Builder.timeout]. * - * Unlike [repoInfo], this method doesn't throw if the JSON field has an unexpected type. + * This unboxed primitive overload exists for backwards compatibility. */ - @JsonProperty("repo_info") @ExcludeMissing fun _repoInfo(): JsonField = repoInfo + fun timeout(timeout: Double) = timeout(timeout as Double?) + + /** Alias for calling [Builder.timeout] with `timeout.orElse(null)`. */ + fun timeout(timeout: Optional) = timeout(timeout.getOrNull()) /** - * Returns the raw JSON value of [stream]. + * Sets [Builder.timeout] to an arbitrary JSON value. * - * Unlike [stream], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("stream") @ExcludeMissing fun _stream(): JsonField = stream + fun timeout(timeout: JsonField) = apply { body.timeout(timeout) } /** - * Returns the raw JSON value of [timeout]. + * The number of times to run the evaluator per input. This is useful for evaluating + * applications that have non-deterministic behavior and gives you both a stronger aggregate + * measure and a sense of the variance in the results. + */ + fun trialCount(trialCount: Double?) = apply { body.trialCount(trialCount) } + + /** + * Alias for [Builder.trialCount]. * - * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + * This unboxed primitive overload exists for backwards compatibility. */ - @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + fun trialCount(trialCount: Double) = trialCount(trialCount as Double?) + + /** Alias for calling [Builder.trialCount] with `trialCount.orElse(null)`. */ + fun trialCount(trialCount: Optional) = trialCount(trialCount.getOrNull()) /** - * Returns the raw JSON value of [trialCount]. + * Sets [Builder.trialCount] to an arbitrary JSON value. * - * Unlike [trialCount], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.trialCount] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("trial_count") - @ExcludeMissing - fun _trialCount(): JsonField = trialCount + fun trialCount(trialCount: JsonField) = apply { body.trialCount(trialCount) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var validated: Boolean = false + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - fun validate(): Body = apply { - if (validated) { - return@apply + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - data().validate() - projectId() - scores().forEach { it.validate() } - task().validate() - baseExperimentId() - baseExperimentName() - experimentName() - gitMetadataSettings().ifPresent { it.validate() } - isPublic() - maxConcurrency() - metadata().ifPresent { it.validate() } - parent().ifPresent { it.validate() } - repoInfo().ifPresent { it.validate() } - stream() - timeout() - trialCount() - validated = true + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - fun toBuilder() = Builder().from(this) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - companion object { + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .data() - * .projectId() - * .scores() - * .task() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - private var data: JsonField? = null - private var projectId: JsonField? = null - private var scores: JsonField>? = null - private var task: JsonField? = null - private var baseExperimentId: JsonField = JsonMissing.of() - private var baseExperimentName: JsonField = JsonMissing.of() - private var experimentName: JsonField = JsonMissing.of() - private var gitMetadataSettings: JsonField = JsonMissing.of() - private var isPublic: JsonField = JsonMissing.of() - private var maxConcurrency: JsonField = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var parent: JsonField = JsonMissing.of() - private var repoInfo: JsonField = JsonMissing.of() - private var stream: JsonField = JsonMissing.of() - private var timeout: JsonField = JsonMissing.of() - private var trialCount: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - @JvmSynthetic - internal fun from(body: Body) = apply { - data = body.data - projectId = body.projectId - scores = body.scores.map { it.toMutableList() } - task = body.task - baseExperimentId = body.baseExperimentId - baseExperimentName = body.baseExperimentName - experimentName = body.experimentName - gitMetadataSettings = body.gitMetadataSettings - isPublic = body.isPublic - maxConcurrency = body.maxConcurrency - metadata = body.metadata - parent = body.parent - repoInfo = body.repoInfo - stream = body.stream - timeout = body.timeout - trialCount = body.trialCount - additionalProperties = body.additionalProperties.toMutableMap() - } + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** The dataset to use */ - fun data(data: Data) = data(JsonField.of(data)) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * Sets [Builder.data] to an arbitrary JSON value. - * - * You should usually call [Builder.data] with a well-typed [Data] 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 replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** Alias for calling [data] with `Data.ofDatasetId(datasetId)`. */ - fun data(datasetId: Data.DatasetId) = data(Data.ofDatasetId(datasetId)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [data] with `Data.ofProjectDatasetName(projectDatasetName)`. */ - fun data(projectDatasetName: Data.ProjectDatasetName) = - data(Data.ofProjectDatasetName(projectDatasetName)) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [data] with `Data.ofDatasetRows(datasetRows)`. */ - fun data(datasetRows: Data.DatasetRows) = data(Data.ofDatasetRows(datasetRows)) + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - /** Unique identifier for the project to run the eval in */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - /** - * Sets [Builder.projectId] to an arbitrary JSON value. - * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - /** The functions to score the eval on */ - fun scores(scores: List) = scores(JsonField.of(scores)) + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - /** - * Sets [Builder.scores] to an arbitrary JSON value. - * - * You should usually call [Builder.scores] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun scores(scores: JsonField>) = apply { - this.scores = scores.map { it.toMutableList() } - } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - /** - * Adds a single [Score] to [scores]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addScore(score: Score) = apply { - scores = - (scores ?: JsonField.of(mutableListOf())).also { - checkKnown("scores", it).add(score) - } - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** Alias for calling [addScore] with `Score.ofFunctionId(functionId)`. */ - fun addScore(functionId: Score.FunctionId) = addScore(Score.ofFunctionId(functionId)) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - /** Alias for calling [addScore] with `Score.ofProjectSlug(projectSlug)`. */ - fun addScore(projectSlug: Score.ProjectSlug) = - addScore(Score.ofProjectSlug(projectSlug)) + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - /** Alias for calling [addScore] with `Score.ofGlobalFunction(globalFunction)`. */ - fun addScore(globalFunction: Score.GlobalFunction) = - addScore(Score.ofGlobalFunction(globalFunction)) + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } - /** Alias for calling [addScore] with `Score.ofPromptSessionId(promptSessionId)`. */ - fun addScore(promptSessionId: Score.PromptSessionId) = - addScore(Score.ofPromptSessionId(promptSessionId)) + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - /** Alias for calling [addScore] with `Score.ofInlineCode(inlineCode)`. */ - fun addScore(inlineCode: Score.InlineCode) = addScore(Score.ofInlineCode(inlineCode)) + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - /** Alias for calling [addScore] with `Score.ofInlinePrompt(inlinePrompt)`. */ - fun addScore(inlinePrompt: Score.InlinePrompt) = - addScore(Score.ofInlinePrompt(inlinePrompt)) + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - /** The function to evaluate */ - fun task(task: Task) = task(JsonField.of(task)) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - /** - * Sets [Builder.task] to an arbitrary JSON value. - * - * You should usually call [Builder.task] with a well-typed [Task] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun task(task: JsonField) = apply { this.task = task } + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } - /** Alias for calling [task] with `Task.ofFunctionId(functionId)`. */ - fun task(functionId: Task.FunctionId) = task(Task.ofFunctionId(functionId)) + /** + * Returns an immutable instance of [EvalCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .data() + * .projectId() + * .scores() + * .task() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): EvalCreateParams = + EvalCreateParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + } - /** Alias for calling [task] with `Task.ofProjectSlug(projectSlug)`. */ - fun task(projectSlug: Task.ProjectSlug) = task(Task.ofProjectSlug(projectSlug)) + fun _body(): Body = body - /** Alias for calling [task] with `Task.ofGlobalFunction(globalFunction)`. */ - fun task(globalFunction: Task.GlobalFunction) = - task(Task.ofGlobalFunction(globalFunction)) + override fun _headers(): Headers = additionalHeaders - /** Alias for calling [task] with `Task.ofPromptSessionId(promptSessionId)`. */ - fun task(promptSessionId: Task.PromptSessionId) = - task(Task.ofPromptSessionId(promptSessionId)) + override fun _queryParams(): QueryParams = additionalQueryParams - /** Alias for calling [task] with `Task.ofInlineCode(inlineCode)`. */ - fun task(inlineCode: Task.InlineCode) = task(Task.ofInlineCode(inlineCode)) + class Body + private constructor( + private val data: JsonField, + private val projectId: JsonField, + private val scores: JsonField>, + private val task: JsonField, + private val baseExperimentId: JsonField, + private val baseExperimentName: JsonField, + private val experimentName: JsonField, + private val gitMetadataSettings: JsonField, + private val isPublic: JsonField, + private val maxConcurrency: JsonField, + private val metadata: JsonField, + private val parent: JsonField, + private val repoInfo: JsonField, + private val stream: JsonField, + private val timeout: JsonField, + private val trialCount: JsonField, + private val additionalProperties: MutableMap, + ) { - /** Alias for calling [task] with `Task.ofInlinePrompt(inlinePrompt)`. */ - fun task(inlinePrompt: Task.InlinePrompt) = task(Task.ofInlinePrompt(inlinePrompt)) + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("project_id") + @ExcludeMissing + projectId: JsonField = JsonMissing.of(), + @JsonProperty("scores") + @ExcludeMissing + scores: JsonField> = JsonMissing.of(), + @JsonProperty("task") @ExcludeMissing task: JsonField = JsonMissing.of(), + @JsonProperty("base_experiment_id") + @ExcludeMissing + baseExperimentId: JsonField = JsonMissing.of(), + @JsonProperty("base_experiment_name") + @ExcludeMissing + baseExperimentName: JsonField = JsonMissing.of(), + @JsonProperty("experiment_name") + @ExcludeMissing + experimentName: JsonField = JsonMissing.of(), + @JsonProperty("git_metadata_settings") + @ExcludeMissing + gitMetadataSettings: JsonField = JsonMissing.of(), + @JsonProperty("is_public") + @ExcludeMissing + isPublic: JsonField = JsonMissing.of(), + @JsonProperty("max_concurrency") + @ExcludeMissing + maxConcurrency: JsonField = JsonMissing.of(), + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), + @JsonProperty("parent") @ExcludeMissing parent: JsonField = JsonMissing.of(), + @JsonProperty("repo_info") + @ExcludeMissing + repoInfo: JsonField = JsonMissing.of(), + @JsonProperty("stream") @ExcludeMissing stream: JsonField = JsonMissing.of(), + @JsonProperty("timeout") @ExcludeMissing timeout: JsonField = JsonMissing.of(), + @JsonProperty("trial_count") + @ExcludeMissing + trialCount: JsonField = JsonMissing.of(), + ) : this( + data, + projectId, + scores, + task, + baseExperimentId, + baseExperimentName, + experimentName, + gitMetadataSettings, + isPublic, + maxConcurrency, + metadata, + parent, + repoInfo, + stream, + timeout, + trialCount, + mutableMapOf(), + ) - /** - * An optional experiment id to use as a base. If specified, the new experiment will be - * summarized and compared to this experiment. - */ - fun baseExperimentId(baseExperimentId: String?) = - baseExperimentId(JsonField.ofNullable(baseExperimentId)) + /** + * The dataset to use + * + * @throws BraintrustInvalidDataException 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(): Data = data.getRequired("data") - /** - * Alias for calling [Builder.baseExperimentId] with `baseExperimentId.orElse(null)`. - */ - fun baseExperimentId(baseExperimentId: Optional) = - baseExperimentId(baseExperimentId.getOrNull()) + /** + * Unique identifier for the project to run the eval in + * + * @throws BraintrustInvalidDataException 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 projectId(): String = projectId.getRequired("project_id") - /** - * Sets [Builder.baseExperimentId] to an arbitrary JSON value. - * - * You should usually call [Builder.baseExperimentId] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun baseExperimentId(baseExperimentId: JsonField) = apply { - this.baseExperimentId = baseExperimentId - } - - /** - * An optional experiment name to use as a base. If specified, the new experiment will - * be summarized and compared to this experiment. - */ - fun baseExperimentName(baseExperimentName: String?) = - baseExperimentName(JsonField.ofNullable(baseExperimentName)) - - /** - * Alias for calling [Builder.baseExperimentName] with - * `baseExperimentName.orElse(null)`. - */ - fun baseExperimentName(baseExperimentName: Optional) = - baseExperimentName(baseExperimentName.getOrNull()) - - /** - * Sets [Builder.baseExperimentName] to an arbitrary JSON value. - * - * You should usually call [Builder.baseExperimentName] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun baseExperimentName(baseExperimentName: JsonField) = apply { - this.baseExperimentName = baseExperimentName - } - - /** - * An optional name for the experiment created by this eval. If it conflicts with an - * existing experiment, it will be suffixed with a unique identifier. - */ - fun experimentName(experimentName: String) = - experimentName(JsonField.of(experimentName)) - - /** - * Sets [Builder.experimentName] to an arbitrary JSON value. - * - * You should usually call [Builder.experimentName] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun experimentName(experimentName: JsonField) = apply { - this.experimentName = experimentName - } - - /** - * Optional settings for collecting git metadata. By default, will collect all git - * metadata fields allowed in org-level settings. - */ - fun gitMetadataSettings(gitMetadataSettings: GitMetadataSettings?) = - gitMetadataSettings(JsonField.ofNullable(gitMetadataSettings)) - - /** - * Alias for calling [Builder.gitMetadataSettings] with - * `gitMetadataSettings.orElse(null)`. - */ - fun gitMetadataSettings(gitMetadataSettings: Optional) = - gitMetadataSettings(gitMetadataSettings.getOrNull()) - - /** - * Sets [Builder.gitMetadataSettings] to an arbitrary JSON value. - * - * You should usually call [Builder.gitMetadataSettings] with a well-typed - * [GitMetadataSettings] value instead. This method is primarily for setting the field - * to an undocumented or not yet supported value. - */ - fun gitMetadataSettings(gitMetadataSettings: JsonField) = apply { - this.gitMetadataSettings = gitMetadataSettings - } - - /** Whether the experiment should be public. Defaults to false. */ - fun isPublic(isPublic: Boolean?) = isPublic(JsonField.ofNullable(isPublic)) - - /** - * Alias for [Builder.isPublic]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun isPublic(isPublic: Boolean) = isPublic(isPublic as Boolean?) - - /** Alias for calling [Builder.isPublic] with `isPublic.orElse(null)`. */ - fun isPublic(isPublic: Optional) = isPublic(isPublic.getOrNull()) - - /** - * Sets [Builder.isPublic] to an arbitrary JSON value. - * - * You should usually call [Builder.isPublic] with a well-typed [Boolean] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun isPublic(isPublic: JsonField) = apply { this.isPublic = isPublic } - - /** - * The maximum number of tasks/scorers that will be run concurrently. Defaults to - * undefined, in which case there is no max concurrency. - */ - fun maxConcurrency(maxConcurrency: Double?) = - maxConcurrency(JsonField.ofNullable(maxConcurrency)) - - /** - * Alias for [Builder.maxConcurrency]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun maxConcurrency(maxConcurrency: Double) = maxConcurrency(maxConcurrency as Double?) - - /** Alias for calling [Builder.maxConcurrency] with `maxConcurrency.orElse(null)`. */ - fun maxConcurrency(maxConcurrency: Optional) = - maxConcurrency(maxConcurrency.getOrNull()) - - /** - * Sets [Builder.maxConcurrency] to an arbitrary JSON value. - * - * You should usually call [Builder.maxConcurrency] with a well-typed [Double] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun maxConcurrency(maxConcurrency: JsonField) = apply { - this.maxConcurrency = maxConcurrency - } - - /** - * Optional experiment-level metadata to store about the evaluation. You can later use - * this to slice & dice across experiments. - */ - 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 } - - /** Options for tracing the evaluation */ - fun parent(parent: Parent) = parent(JsonField.of(parent)) - - /** - * Sets [Builder.parent] to an arbitrary JSON value. - * - * You should usually call [Builder.parent] with a well-typed [Parent] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun parent(parent: JsonField) = apply { this.parent = parent } - - /** Alias for calling [parent] with `Parent.ofSpanParentStruct(spanParentStruct)`. */ - fun parent(spanParentStruct: Parent.SpanParentStruct) = - parent(Parent.ofSpanParentStruct(spanParentStruct)) - - /** Alias for calling [parent] with `Parent.ofString(string)`. */ - fun parent(string: String) = parent(Parent.ofString(string)) - - /** Metadata about the state of the repo when the experiment was created */ - fun repoInfo(repoInfo: RepoInfo?) = repoInfo(JsonField.ofNullable(repoInfo)) - - /** Alias for calling [Builder.repoInfo] with `repoInfo.orElse(null)`. */ - fun repoInfo(repoInfo: Optional) = repoInfo(repoInfo.getOrNull()) - - /** - * Sets [Builder.repoInfo] to an arbitrary JSON value. - * - * You should usually call [Builder.repoInfo] with a well-typed [RepoInfo] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun repoInfo(repoInfo: JsonField) = apply { this.repoInfo = repoInfo } - - /** - * Whether to stream the results of the eval. If true, the request will return two - * events: one to indicate the experiment has started, and another upon completion. If - * false, the request will return the evaluation's summary upon completion. - */ - fun stream(stream: Boolean) = stream(JsonField.of(stream)) - - /** - * Sets [Builder.stream] to an arbitrary JSON value. - * - * You should usually call [Builder.stream] with a well-typed [Boolean] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun stream(stream: JsonField) = apply { this.stream = stream } - - /** - * The maximum duration, in milliseconds, to run the evaluation. Defaults to undefined, - * in which case there is no timeout. - */ - fun timeout(timeout: Double?) = timeout(JsonField.ofNullable(timeout)) + /** + * The functions to score the eval on + * + * @throws BraintrustInvalidDataException 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 scores(): List = scores.getRequired("scores") - /** - * Alias for [Builder.timeout]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun timeout(timeout: Double) = timeout(timeout as Double?) + /** + * The function to evaluate + * + * @throws BraintrustInvalidDataException 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 task(): Task = task.getRequired("task") - /** Alias for calling [Builder.timeout] with `timeout.orElse(null)`. */ - fun timeout(timeout: Optional) = timeout(timeout.getOrNull()) + /** + * An optional experiment id to use as a base. If specified, the new experiment will be + * summarized and compared to this experiment. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseExperimentId(): Optional = + baseExperimentId.getOptional("base_experiment_id") - /** - * 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 } + /** + * An optional experiment name to use as a base. If specified, the new experiment will be + * summarized and compared to this experiment. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseExperimentName(): Optional = + baseExperimentName.getOptional("base_experiment_name") - /** - * The number of times to run the evaluator per input. This is useful for evaluating - * applications that have non-deterministic behavior and gives you both a stronger - * aggregate measure and a sense of the variance in the results. - */ - fun trialCount(trialCount: Double?) = trialCount(JsonField.ofNullable(trialCount)) + /** + * An optional name for the experiment created by this eval. If it conflicts with an + * existing experiment, it will be suffixed with a unique identifier. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun experimentName(): Optional = experimentName.getOptional("experiment_name") - /** - * Alias for [Builder.trialCount]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun trialCount(trialCount: Double) = trialCount(trialCount as Double?) + /** + * Optional settings for collecting git metadata. By default, will collect all git metadata + * fields allowed in org-level settings. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun gitMetadataSettings(): Optional = + gitMetadataSettings.getOptional("git_metadata_settings") - /** Alias for calling [Builder.trialCount] with `trialCount.orElse(null)`. */ - fun trialCount(trialCount: Optional) = trialCount(trialCount.getOrNull()) + /** + * Whether the experiment should be public. Defaults to false. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun isPublic(): Optional = isPublic.getOptional("is_public") - /** - * Sets [Builder.trialCount] to an arbitrary JSON value. - * - * You should usually call [Builder.trialCount] with a well-typed [Double] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun trialCount(trialCount: JsonField) = apply { this.trialCount = trialCount } + /** + * The maximum number of tasks/scorers that will be run concurrently. Defaults to undefined, + * in which case there is no max concurrency. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun maxConcurrency(): Optional = maxConcurrency.getOptional("max_concurrency") - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + /** + * Optional experiment-level metadata to store about the evaluation. You can later use this + * to slice & dice across experiments. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + /** + * Options for tracing the evaluation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun parent(): Optional = parent.getOptional("parent") - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + /** + * Metadata about the state of the repo when the experiment was created + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun repoInfo(): Optional = repoInfo.getOptional("repo_info") - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + /** + * Whether to stream the results of the eval. If true, the request will return two events: + * one to indicate the experiment has started, and another upon completion. If false, the + * request will return the evaluation's summary upon completion. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun stream(): Optional = stream.getOptional("stream") - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + /** + * The maximum duration, in milliseconds, to run the evaluation. Defaults to undefined, in + * which case there is no timeout. + * + * @throws BraintrustInvalidDataException 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 an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .data() - * .projectId() - * .scores() - * .task() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("data", data), - checkRequired("projectId", projectId), - checkRequired("scores", scores).map { it.toImmutable() }, - checkRequired("task", task), - baseExperimentId, - baseExperimentName, - experimentName, - gitMetadataSettings, - isPublic, - maxConcurrency, - metadata, - parent, - repoInfo, - stream, - timeout, - trialCount, - additionalProperties.toImmutable(), - ) - } + /** + * The number of times to run the evaluator per input. This is useful for evaluating + * applications that have non-deterministic behavior and gives you both a stronger aggregate + * measure and a sense of the variance in the results. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun trialCount(): Optional = trialCount.getOptional("trial_count") - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** + * 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 - return /* spotless:off */ other is Body && data == other.data && projectId == other.projectId && scores == other.scores && task == other.task && baseExperimentId == other.baseExperimentId && baseExperimentName == other.baseExperimentName && experimentName == other.experimentName && gitMetadataSettings == other.gitMetadataSettings && isPublic == other.isPublic && maxConcurrency == other.maxConcurrency && metadata == other.metadata && parent == other.parent && repoInfo == other.repoInfo && stream == other.stream && timeout == other.timeout && trialCount == other.trialCount && additionalProperties == other.additionalProperties /* spotless:on */ - } + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(data, projectId, scores, task, baseExperimentId, baseExperimentName, experimentName, gitMetadataSettings, isPublic, maxConcurrency, metadata, parent, repoInfo, stream, timeout, trialCount, additionalProperties) } - /* spotless:on */ + /** + * Returns the raw JSON value of [scores]. + * + * Unlike [scores], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("scores") @ExcludeMissing fun _scores(): JsonField> = scores - override fun hashCode(): Int = hashCode + /** + * Returns the raw JSON value of [task]. + * + * Unlike [task], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("task") @ExcludeMissing fun _task(): JsonField = task - override fun toString() = - "Body{data=$data, projectId=$projectId, scores=$scores, task=$task, baseExperimentId=$baseExperimentId, baseExperimentName=$baseExperimentName, experimentName=$experimentName, gitMetadataSettings=$gitMetadataSettings, isPublic=$isPublic, maxConcurrency=$maxConcurrency, metadata=$metadata, parent=$parent, repoInfo=$repoInfo, stream=$stream, timeout=$timeout, trialCount=$trialCount, additionalProperties=$additionalProperties}" - } + /** + * Returns the raw JSON value of [baseExperimentId]. + * + * Unlike [baseExperimentId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("base_experiment_id") + @ExcludeMissing + fun _baseExperimentId(): JsonField = baseExperimentId - fun toBuilder() = Builder().from(this) + /** + * Returns the raw JSON value of [baseExperimentName]. + * + * Unlike [baseExperimentName], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("base_experiment_name") + @ExcludeMissing + fun _baseExperimentName(): JsonField = baseExperimentName - companion object { + /** + * Returns the raw JSON value of [experimentName]. + * + * Unlike [experimentName], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("experiment_name") + @ExcludeMissing + fun _experimentName(): JsonField = experimentName /** - * Returns a mutable builder for constructing an instance of [EvalCreateParams]. + * Returns the raw JSON value of [gitMetadataSettings]. * - * The following fields are required: - * ```java - * .data() - * .projectId() - * .scores() - * .task() - * ``` + * Unlike [gitMetadataSettings], this method doesn't throw if the JSON field has an + * unexpected type. */ - @JvmStatic fun builder() = Builder() - } + @JsonProperty("git_metadata_settings") + @ExcludeMissing + fun _gitMetadataSettings(): JsonField = gitMetadataSettings - /** A builder for [EvalCreateParams]. */ - @NoAutoDetect - class Builder internal constructor() { + /** + * Returns the raw JSON value of [isPublic]. + * + * Unlike [isPublic], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("is_public") @ExcludeMissing fun _isPublic(): JsonField = isPublic - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + /** + * Returns the raw JSON value of [maxConcurrency]. + * + * Unlike [maxConcurrency], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("max_concurrency") + @ExcludeMissing + fun _maxConcurrency(): JsonField = maxConcurrency - @JvmSynthetic - internal fun from(evalCreateParams: EvalCreateParams) = apply { - body = evalCreateParams.body.toBuilder() - additionalHeaders = evalCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = evalCreateParams.additionalQueryParams.toBuilder() - } + /** + * 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 - /** The dataset to use */ - fun data(data: Data) = apply { body.data(data) } + /** + * Returns the raw JSON value of [parent]. + * + * Unlike [parent], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("parent") @ExcludeMissing fun _parent(): JsonField = parent /** - * Sets [Builder.data] to an arbitrary JSON value. + * Returns the raw JSON value of [repoInfo]. * - * You should usually call [Builder.data] with a well-typed [Data] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [repoInfo], this method doesn't throw if the JSON field has an unexpected type. */ - fun data(data: JsonField) = apply { body.data(data) } - - /** Alias for calling [data] with `Data.ofDatasetId(datasetId)`. */ - fun data(datasetId: Data.DatasetId) = apply { body.data(datasetId) } - - /** Alias for calling [data] with `Data.ofProjectDatasetName(projectDatasetName)`. */ - fun data(projectDatasetName: Data.ProjectDatasetName) = apply { - body.data(projectDatasetName) - } - - /** Alias for calling [data] with `Data.ofDatasetRows(datasetRows)`. */ - fun data(datasetRows: Data.DatasetRows) = apply { body.data(datasetRows) } - - /** Unique identifier for the project to run the eval in */ - fun projectId(projectId: String) = apply { body.projectId(projectId) } + @JsonProperty("repo_info") @ExcludeMissing fun _repoInfo(): JsonField = repoInfo /** - * Sets [Builder.projectId] to an arbitrary JSON value. + * Returns the raw JSON value of [stream]. * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [stream], this method doesn't throw if the JSON field has an unexpected type. */ - fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } - - /** The functions to score the eval on */ - fun scores(scores: List) = apply { body.scores(scores) } + @JsonProperty("stream") @ExcludeMissing fun _stream(): JsonField = stream /** - * Sets [Builder.scores] to an arbitrary JSON value. + * Returns the raw JSON value of [timeout]. * - * You should usually call [Builder.scores] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. */ - fun scores(scores: JsonField>) = apply { body.scores(scores) } + @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout /** - * Adds a single [Score] to [scores]. + * Returns the raw JSON value of [trialCount]. * - * @throws IllegalStateException if the field was previously set to a non-list. + * Unlike [trialCount], this method doesn't throw if the JSON field has an unexpected type. */ - fun addScore(score: Score) = apply { body.addScore(score) } + @JsonProperty("trial_count") + @ExcludeMissing + fun _trialCount(): JsonField = trialCount - /** Alias for calling [addScore] with `Score.ofFunctionId(functionId)`. */ - fun addScore(functionId: Score.FunctionId) = apply { body.addScore(functionId) } + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } - /** Alias for calling [addScore] with `Score.ofProjectSlug(projectSlug)`. */ - fun addScore(projectSlug: Score.ProjectSlug) = apply { body.addScore(projectSlug) } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - /** Alias for calling [addScore] with `Score.ofGlobalFunction(globalFunction)`. */ - fun addScore(globalFunction: Score.GlobalFunction) = apply { body.addScore(globalFunction) } + fun toBuilder() = Builder().from(this) - /** Alias for calling [addScore] with `Score.ofPromptSessionId(promptSessionId)`. */ - fun addScore(promptSessionId: Score.PromptSessionId) = apply { - body.addScore(promptSessionId) + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .data() + * .projectId() + * .scores() + * .task() + * ``` + */ + @JvmStatic fun builder() = Builder() } - /** Alias for calling [addScore] with `Score.ofInlineCode(inlineCode)`. */ - fun addScore(inlineCode: Score.InlineCode) = apply { body.addScore(inlineCode) } + /** A builder for [Body]. */ + class Builder internal constructor() { - /** Alias for calling [addScore] with `Score.ofInlinePrompt(inlinePrompt)`. */ - fun addScore(inlinePrompt: Score.InlinePrompt) = apply { body.addScore(inlinePrompt) } + private var data: JsonField? = null + private var projectId: JsonField? = null + private var scores: JsonField>? = null + private var task: JsonField? = null + private var baseExperimentId: JsonField = JsonMissing.of() + private var baseExperimentName: JsonField = JsonMissing.of() + private var experimentName: JsonField = JsonMissing.of() + private var gitMetadataSettings: JsonField = JsonMissing.of() + private var isPublic: JsonField = JsonMissing.of() + private var maxConcurrency: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var parent: JsonField = JsonMissing.of() + private var repoInfo: JsonField = JsonMissing.of() + private var stream: JsonField = JsonMissing.of() + private var timeout: JsonField = JsonMissing.of() + private var trialCount: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() - /** The function to evaluate */ - fun task(task: Task) = apply { body.task(task) } + @JvmSynthetic + internal fun from(body: Body) = apply { + data = body.data + projectId = body.projectId + scores = body.scores.map { it.toMutableList() } + task = body.task + baseExperimentId = body.baseExperimentId + baseExperimentName = body.baseExperimentName + experimentName = body.experimentName + gitMetadataSettings = body.gitMetadataSettings + isPublic = body.isPublic + maxConcurrency = body.maxConcurrency + metadata = body.metadata + parent = body.parent + repoInfo = body.repoInfo + stream = body.stream + timeout = body.timeout + trialCount = body.trialCount + additionalProperties = body.additionalProperties.toMutableMap() + } - /** - * Sets [Builder.task] to an arbitrary JSON value. - * - * You should usually call [Builder.task] with a well-typed [Task] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun task(task: JsonField) = apply { body.task(task) } + /** The dataset to use */ + fun data(data: Data) = data(JsonField.of(data)) - /** Alias for calling [task] with `Task.ofFunctionId(functionId)`. */ - fun task(functionId: Task.FunctionId) = apply { body.task(functionId) } + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] 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 } - /** Alias for calling [task] with `Task.ofProjectSlug(projectSlug)`. */ - fun task(projectSlug: Task.ProjectSlug) = apply { body.task(projectSlug) } + /** Alias for calling [data] with `Data.ofDatasetId(datasetId)`. */ + fun data(datasetId: Data.DatasetId) = data(Data.ofDatasetId(datasetId)) - /** Alias for calling [task] with `Task.ofGlobalFunction(globalFunction)`. */ - fun task(globalFunction: Task.GlobalFunction) = apply { body.task(globalFunction) } + /** Alias for calling [data] with `Data.ofProjectDatasetName(projectDatasetName)`. */ + fun data(projectDatasetName: Data.ProjectDatasetName) = + data(Data.ofProjectDatasetName(projectDatasetName)) - /** Alias for calling [task] with `Task.ofPromptSessionId(promptSessionId)`. */ - fun task(promptSessionId: Task.PromptSessionId) = apply { body.task(promptSessionId) } + /** Alias for calling [data] with `Data.ofDatasetRows(datasetRows)`. */ + fun data(datasetRows: Data.DatasetRows) = data(Data.ofDatasetRows(datasetRows)) - /** Alias for calling [task] with `Task.ofInlineCode(inlineCode)`. */ - fun task(inlineCode: Task.InlineCode) = apply { body.task(inlineCode) } + /** Unique identifier for the project to run the eval in */ + fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - /** Alias for calling [task] with `Task.ofInlinePrompt(inlinePrompt)`. */ - fun task(inlinePrompt: Task.InlinePrompt) = apply { body.task(inlinePrompt) } + /** + * Sets [Builder.projectId] to an arbitrary JSON value. + * + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun projectId(projectId: JsonField) = apply { this.projectId = projectId } - /** - * An optional experiment id to use as a base. If specified, the new experiment will be - * summarized and compared to this experiment. - */ - fun baseExperimentId(baseExperimentId: String?) = apply { - body.baseExperimentId(baseExperimentId) - } + /** The functions to score the eval on */ + fun scores(scores: List) = scores(JsonField.of(scores)) - /** Alias for calling [Builder.baseExperimentId] with `baseExperimentId.orElse(null)`. */ - fun baseExperimentId(baseExperimentId: Optional) = - baseExperimentId(baseExperimentId.getOrNull()) + /** + * Sets [Builder.scores] to an arbitrary JSON value. + * + * You should usually call [Builder.scores] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun scores(scores: JsonField>) = apply { + this.scores = scores.map { it.toMutableList() } + } - /** - * Sets [Builder.baseExperimentId] to an arbitrary JSON value. - * - * You should usually call [Builder.baseExperimentId] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun baseExperimentId(baseExperimentId: JsonField) = apply { - body.baseExperimentId(baseExperimentId) - } + /** + * Adds a single [Score] to [scores]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addScore(score: Score) = apply { + scores = + (scores ?: JsonField.of(mutableListOf())).also { + checkKnown("scores", it).add(score) + } + } - /** - * An optional experiment name to use as a base. If specified, the new experiment will be - * summarized and compared to this experiment. - */ - fun baseExperimentName(baseExperimentName: String?) = apply { - body.baseExperimentName(baseExperimentName) - } + /** Alias for calling [addScore] with `Score.ofFunctionId(functionId)`. */ + fun addScore(functionId: Score.FunctionId) = addScore(Score.ofFunctionId(functionId)) - /** - * Alias for calling [Builder.baseExperimentName] with `baseExperimentName.orElse(null)`. - */ - fun baseExperimentName(baseExperimentName: Optional) = - baseExperimentName(baseExperimentName.getOrNull()) + /** Alias for calling [addScore] with `Score.ofProjectSlug(projectSlug)`. */ + fun addScore(projectSlug: Score.ProjectSlug) = + addScore(Score.ofProjectSlug(projectSlug)) - /** - * Sets [Builder.baseExperimentName] to an arbitrary JSON value. - * - * You should usually call [Builder.baseExperimentName] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun baseExperimentName(baseExperimentName: JsonField) = apply { - body.baseExperimentName(baseExperimentName) - } + /** Alias for calling [addScore] with `Score.ofGlobalFunction(globalFunction)`. */ + fun addScore(globalFunction: Score.GlobalFunction) = + addScore(Score.ofGlobalFunction(globalFunction)) - /** - * An optional name for the experiment created by this eval. If it conflicts with an - * existing experiment, it will be suffixed with a unique identifier. - */ - fun experimentName(experimentName: String) = apply { body.experimentName(experimentName) } + /** Alias for calling [addScore] with `Score.ofPromptSessionId(promptSessionId)`. */ + fun addScore(promptSessionId: Score.PromptSessionId) = + addScore(Score.ofPromptSessionId(promptSessionId)) + + /** Alias for calling [addScore] with `Score.ofInlineCode(inlineCode)`. */ + fun addScore(inlineCode: Score.InlineCode) = addScore(Score.ofInlineCode(inlineCode)) + + /** Alias for calling [addScore] with `Score.ofInlinePrompt(inlinePrompt)`. */ + fun addScore(inlinePrompt: Score.InlinePrompt) = + addScore(Score.ofInlinePrompt(inlinePrompt)) + + /** The function to evaluate */ + fun task(task: Task) = task(JsonField.of(task)) - /** - * Sets [Builder.experimentName] to an arbitrary JSON value. - * - * You should usually call [Builder.experimentName] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun experimentName(experimentName: JsonField) = apply { - body.experimentName(experimentName) - } + /** + * Sets [Builder.task] to an arbitrary JSON value. + * + * You should usually call [Builder.task] with a well-typed [Task] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun task(task: JsonField) = apply { this.task = task } - /** - * Optional settings for collecting git metadata. By default, will collect all git metadata - * fields allowed in org-level settings. - */ - fun gitMetadataSettings(gitMetadataSettings: GitMetadataSettings?) = apply { - body.gitMetadataSettings(gitMetadataSettings) - } + /** Alias for calling [task] with `Task.ofFunctionId(functionId)`. */ + fun task(functionId: Task.FunctionId) = task(Task.ofFunctionId(functionId)) - /** - * Alias for calling [Builder.gitMetadataSettings] with `gitMetadataSettings.orElse(null)`. - */ - fun gitMetadataSettings(gitMetadataSettings: Optional) = - gitMetadataSettings(gitMetadataSettings.getOrNull()) + /** Alias for calling [task] with `Task.ofProjectSlug(projectSlug)`. */ + fun task(projectSlug: Task.ProjectSlug) = task(Task.ofProjectSlug(projectSlug)) - /** - * Sets [Builder.gitMetadataSettings] to an arbitrary JSON value. - * - * You should usually call [Builder.gitMetadataSettings] with a well-typed - * [GitMetadataSettings] value instead. This method is primarily for setting the field to an - * undocumented or not yet supported value. - */ - fun gitMetadataSettings(gitMetadataSettings: JsonField) = apply { - body.gitMetadataSettings(gitMetadataSettings) - } + /** Alias for calling [task] with `Task.ofGlobalFunction(globalFunction)`. */ + fun task(globalFunction: Task.GlobalFunction) = + task(Task.ofGlobalFunction(globalFunction)) - /** Whether the experiment should be public. Defaults to false. */ - fun isPublic(isPublic: Boolean?) = apply { body.isPublic(isPublic) } + /** Alias for calling [task] with `Task.ofPromptSessionId(promptSessionId)`. */ + fun task(promptSessionId: Task.PromptSessionId) = + task(Task.ofPromptSessionId(promptSessionId)) - /** - * Alias for [Builder.isPublic]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun isPublic(isPublic: Boolean) = isPublic(isPublic as Boolean?) + /** Alias for calling [task] with `Task.ofInlineCode(inlineCode)`. */ + fun task(inlineCode: Task.InlineCode) = task(Task.ofInlineCode(inlineCode)) - /** Alias for calling [Builder.isPublic] with `isPublic.orElse(null)`. */ - fun isPublic(isPublic: Optional) = isPublic(isPublic.getOrNull()) + /** Alias for calling [task] with `Task.ofInlinePrompt(inlinePrompt)`. */ + fun task(inlinePrompt: Task.InlinePrompt) = task(Task.ofInlinePrompt(inlinePrompt)) - /** - * Sets [Builder.isPublic] to an arbitrary JSON value. - * - * You should usually call [Builder.isPublic] with a well-typed [Boolean] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun isPublic(isPublic: JsonField) = apply { body.isPublic(isPublic) } + /** + * An optional experiment id to use as a base. If specified, the new experiment will be + * summarized and compared to this experiment. + */ + fun baseExperimentId(baseExperimentId: String?) = + baseExperimentId(JsonField.ofNullable(baseExperimentId)) - /** - * The maximum number of tasks/scorers that will be run concurrently. Defaults to undefined, - * in which case there is no max concurrency. - */ - fun maxConcurrency(maxConcurrency: Double?) = apply { body.maxConcurrency(maxConcurrency) } + /** + * Alias for calling [Builder.baseExperimentId] with `baseExperimentId.orElse(null)`. + */ + fun baseExperimentId(baseExperimentId: Optional) = + baseExperimentId(baseExperimentId.getOrNull()) - /** - * Alias for [Builder.maxConcurrency]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun maxConcurrency(maxConcurrency: Double) = maxConcurrency(maxConcurrency as Double?) + /** + * Sets [Builder.baseExperimentId] to an arbitrary JSON value. + * + * You should usually call [Builder.baseExperimentId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun baseExperimentId(baseExperimentId: JsonField) = apply { + this.baseExperimentId = baseExperimentId + } - /** Alias for calling [Builder.maxConcurrency] with `maxConcurrency.orElse(null)`. */ - fun maxConcurrency(maxConcurrency: Optional) = - maxConcurrency(maxConcurrency.getOrNull()) + /** + * An optional experiment name to use as a base. If specified, the new experiment will + * be summarized and compared to this experiment. + */ + fun baseExperimentName(baseExperimentName: String?) = + baseExperimentName(JsonField.ofNullable(baseExperimentName)) - /** - * Sets [Builder.maxConcurrency] to an arbitrary JSON value. - * - * You should usually call [Builder.maxConcurrency] with a well-typed [Double] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun maxConcurrency(maxConcurrency: JsonField) = apply { - body.maxConcurrency(maxConcurrency) - } + /** + * Alias for calling [Builder.baseExperimentName] with + * `baseExperimentName.orElse(null)`. + */ + fun baseExperimentName(baseExperimentName: Optional) = + baseExperimentName(baseExperimentName.getOrNull()) - /** - * Optional experiment-level metadata to store about the evaluation. You can later use this - * to slice & dice across experiments. - */ - fun metadata(metadata: Metadata) = apply { body.metadata(metadata) } + /** + * Sets [Builder.baseExperimentName] to an arbitrary JSON value. + * + * You should usually call [Builder.baseExperimentName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun baseExperimentName(baseExperimentName: JsonField) = apply { + this.baseExperimentName = baseExperimentName + } - /** - * 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) } + /** + * An optional name for the experiment created by this eval. If it conflicts with an + * existing experiment, it will be suffixed with a unique identifier. + */ + fun experimentName(experimentName: String) = + experimentName(JsonField.of(experimentName)) - /** Options for tracing the evaluation */ - fun parent(parent: Parent) = apply { body.parent(parent) } + /** + * Sets [Builder.experimentName] to an arbitrary JSON value. + * + * You should usually call [Builder.experimentName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun experimentName(experimentName: JsonField) = apply { + this.experimentName = experimentName + } - /** - * Sets [Builder.parent] to an arbitrary JSON value. - * - * You should usually call [Builder.parent] with a well-typed [Parent] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun parent(parent: JsonField) = apply { body.parent(parent) } + /** + * Optional settings for collecting git metadata. By default, will collect all git + * metadata fields allowed in org-level settings. + */ + fun gitMetadataSettings(gitMetadataSettings: GitMetadataSettings?) = + gitMetadataSettings(JsonField.ofNullable(gitMetadataSettings)) - /** Alias for calling [parent] with `Parent.ofSpanParentStruct(spanParentStruct)`. */ - fun parent(spanParentStruct: Parent.SpanParentStruct) = apply { - body.parent(spanParentStruct) - } + /** + * Alias for calling [Builder.gitMetadataSettings] with + * `gitMetadataSettings.orElse(null)`. + */ + fun gitMetadataSettings(gitMetadataSettings: Optional) = + gitMetadataSettings(gitMetadataSettings.getOrNull()) - /** Alias for calling [parent] with `Parent.ofString(string)`. */ - fun parent(string: String) = apply { body.parent(string) } + /** + * Sets [Builder.gitMetadataSettings] to an arbitrary JSON value. + * + * You should usually call [Builder.gitMetadataSettings] with a well-typed + * [GitMetadataSettings] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun gitMetadataSettings(gitMetadataSettings: JsonField) = apply { + this.gitMetadataSettings = gitMetadataSettings + } - /** Metadata about the state of the repo when the experiment was created */ - fun repoInfo(repoInfo: RepoInfo?) = apply { body.repoInfo(repoInfo) } + /** Whether the experiment should be public. Defaults to false. */ + fun isPublic(isPublic: Boolean?) = isPublic(JsonField.ofNullable(isPublic)) - /** Alias for calling [Builder.repoInfo] with `repoInfo.orElse(null)`. */ - fun repoInfo(repoInfo: Optional) = repoInfo(repoInfo.getOrNull()) + /** + * Alias for [Builder.isPublic]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun isPublic(isPublic: Boolean) = isPublic(isPublic as Boolean?) - /** - * Sets [Builder.repoInfo] to an arbitrary JSON value. - * - * You should usually call [Builder.repoInfo] with a well-typed [RepoInfo] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun repoInfo(repoInfo: JsonField) = apply { body.repoInfo(repoInfo) } + /** Alias for calling [Builder.isPublic] with `isPublic.orElse(null)`. */ + fun isPublic(isPublic: Optional) = isPublic(isPublic.getOrNull()) - /** - * Whether to stream the results of the eval. If true, the request will return two events: - * one to indicate the experiment has started, and another upon completion. If false, the - * request will return the evaluation's summary upon completion. - */ - fun stream(stream: Boolean) = apply { body.stream(stream) } + /** + * Sets [Builder.isPublic] to an arbitrary JSON value. + * + * You should usually call [Builder.isPublic] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isPublic(isPublic: JsonField) = apply { this.isPublic = isPublic } - /** - * 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) } + /** + * The maximum number of tasks/scorers that will be run concurrently. Defaults to + * undefined, in which case there is no max concurrency. + */ + fun maxConcurrency(maxConcurrency: Double?) = + maxConcurrency(JsonField.ofNullable(maxConcurrency)) - /** - * The maximum duration, in milliseconds, to run the evaluation. Defaults to undefined, in - * which case there is no timeout. - */ - fun timeout(timeout: Double?) = apply { body.timeout(timeout) } + /** + * Alias for [Builder.maxConcurrency]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxConcurrency(maxConcurrency: Double) = maxConcurrency(maxConcurrency as Double?) - /** - * Alias for [Builder.timeout]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun timeout(timeout: Double) = timeout(timeout as Double?) + /** Alias for calling [Builder.maxConcurrency] with `maxConcurrency.orElse(null)`. */ + fun maxConcurrency(maxConcurrency: Optional) = + maxConcurrency(maxConcurrency.getOrNull()) - /** Alias for calling [Builder.timeout] with `timeout.orElse(null)`. */ - fun timeout(timeout: Optional) = timeout(timeout.getOrNull()) + /** + * Sets [Builder.maxConcurrency] to an arbitrary JSON value. + * + * You should usually call [Builder.maxConcurrency] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxConcurrency(maxConcurrency: JsonField) = apply { + this.maxConcurrency = maxConcurrency + } - /** - * 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 { body.timeout(timeout) } + /** + * Optional experiment-level metadata to store about the evaluation. You can later use + * this to slice & dice across experiments. + */ + fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) - /** - * The number of times to run the evaluator per input. This is useful for evaluating - * applications that have non-deterministic behavior and gives you both a stronger aggregate - * measure and a sense of the variance in the results. - */ - fun trialCount(trialCount: Double?) = apply { body.trialCount(trialCount) } + /** + * 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 } - /** - * Alias for [Builder.trialCount]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun trialCount(trialCount: Double) = trialCount(trialCount as Double?) + /** Options for tracing the evaluation */ + fun parent(parent: Parent) = parent(JsonField.of(parent)) - /** Alias for calling [Builder.trialCount] with `trialCount.orElse(null)`. */ - fun trialCount(trialCount: Optional) = trialCount(trialCount.getOrNull()) + /** + * Sets [Builder.parent] to an arbitrary JSON value. + * + * You should usually call [Builder.parent] with a well-typed [Parent] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun parent(parent: JsonField) = apply { this.parent = parent } - /** - * Sets [Builder.trialCount] to an arbitrary JSON value. - * - * You should usually call [Builder.trialCount] with a well-typed [Double] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun trialCount(trialCount: JsonField) = apply { body.trialCount(trialCount) } + /** Alias for calling [parent] with `Parent.ofSpanParentStruct(spanParentStruct)`. */ + fun parent(spanParentStruct: Parent.SpanParentStruct) = + parent(Parent.ofSpanParentStruct(spanParentStruct)) - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) - } + /** Alias for calling [parent] with `Parent.ofString(string)`. */ + fun parent(string: String) = parent(Parent.ofString(string)) - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } + /** Metadata about the state of the repo when the experiment was created */ + fun repoInfo(repoInfo: RepoInfo?) = repoInfo(JsonField.ofNullable(repoInfo)) - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) - } + /** Alias for calling [Builder.repoInfo] with `repoInfo.orElse(null)`. */ + fun repoInfo(repoInfo: Optional) = repoInfo(repoInfo.getOrNull()) - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** + * Sets [Builder.repoInfo] to an arbitrary JSON value. + * + * You should usually call [Builder.repoInfo] with a well-typed [RepoInfo] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun repoInfo(repoInfo: JsonField) = apply { this.repoInfo = repoInfo } - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** + * Whether to stream the results of the eval. If true, the request will return two + * events: one to indicate the experiment has started, and another upon completion. If + * false, the request will return the evaluation's summary upon completion. + */ + fun stream(stream: Boolean) = stream(JsonField.of(stream)) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * 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 additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * The maximum duration, in milliseconds, to run the evaluation. Defaults to undefined, + * in which case there is no timeout. + */ + fun timeout(timeout: Double?) = timeout(JsonField.ofNullable(timeout)) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** + * Alias for [Builder.timeout]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun timeout(timeout: Double) = timeout(timeout as Double?) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** Alias for calling [Builder.timeout] with `timeout.orElse(null)`. */ + fun timeout(timeout: Optional) = timeout(timeout.getOrNull()) - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * 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 putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * The number of times to run the evaluator per input. This is useful for evaluating + * applications that have non-deterministic behavior and gives you both a stronger + * aggregate measure and a sense of the variance in the results. + */ + fun trialCount(trialCount: Double?) = trialCount(JsonField.ofNullable(trialCount)) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Alias for [Builder.trialCount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun trialCount(trialCount: Double) = trialCount(trialCount as Double?) - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** Alias for calling [Builder.trialCount] with `trialCount.orElse(null)`. */ + fun trialCount(trialCount: Optional) = trialCount(trialCount.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.trialCount] to an arbitrary JSON value. + * + * You should usually call [Builder.trialCount] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun trialCount(trialCount: JsonField) = apply { this.trialCount = trialCount } - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) + 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 + * .data() + * .projectId() + * .scores() + * .task() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("data", data), + checkRequired("projectId", projectId), + checkRequired("scores", scores).map { it.toImmutable() }, + checkRequired("task", task), + baseExperimentId, + baseExperimentName, + experimentName, + gitMetadataSettings, + isPublic, + maxConcurrency, + metadata, + parent, + repoInfo, + stream, + timeout, + trialCount, + additionalProperties.toMutableMap(), + ) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + private var validated: Boolean = false - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun validate(): Body = apply { + if (validated) { + return@apply + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) + data().validate() + projectId() + scores().forEach { it.validate() } + task().validate() + baseExperimentId() + baseExperimentName() + experimentName() + gitMetadataSettings().ifPresent { it.validate() } + isPublic() + maxConcurrency() + metadata().ifPresent { it.validate() } + parent().ifPresent { it.validate() } + repoInfo().ifPresent { it.validate() } + stream() + timeout() + trialCount() + validated = true } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (data.asKnown().getOrNull()?.validity() ?: 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (scores.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (task.asKnown().getOrNull()?.validity() ?: 0) + + (if (baseExperimentId.asKnown().isPresent) 1 else 0) + + (if (baseExperimentName.asKnown().isPresent) 1 else 0) + + (if (experimentName.asKnown().isPresent) 1 else 0) + + (gitMetadataSettings.asKnown().getOrNull()?.validity() ?: 0) + + (if (isPublic.asKnown().isPresent) 1 else 0) + + (if (maxConcurrency.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (parent.asKnown().getOrNull()?.validity() ?: 0) + + (repoInfo.asKnown().getOrNull()?.validity() ?: 0) + + (if (stream.asKnown().isPresent) 1 else 0) + + (if (timeout.asKnown().isPresent) 1 else 0) + + (if (trialCount.asKnown().isPresent) 1 else 0) - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + return /* spotless:off */ other is Body && data == other.data && projectId == other.projectId && scores == other.scores && task == other.task && baseExperimentId == other.baseExperimentId && baseExperimentName == other.baseExperimentName && experimentName == other.experimentName && gitMetadataSettings == other.gitMetadataSettings && isPublic == other.isPublic && maxConcurrency == other.maxConcurrency && metadata == other.metadata && parent == other.parent && repoInfo == other.repoInfo && stream == other.stream && timeout == other.timeout && trialCount == other.trialCount && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(data, projectId, scores, task, baseExperimentId, baseExperimentName, experimentName, gitMetadataSettings, isPublic, maxConcurrency, metadata, parent, repoInfo, stream, timeout, trialCount, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [EvalCreateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .data() - * .projectId() - * .scores() - * .task() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): EvalCreateParams = - EvalCreateParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + override fun toString() = + "Body{data=$data, projectId=$projectId, scores=$scores, task=$task, baseExperimentId=$baseExperimentId, baseExperimentName=$baseExperimentName, experimentName=$experimentName, gitMetadataSettings=$gitMetadataSettings, isPublic=$isPublic, maxConcurrency=$maxConcurrency, metadata=$metadata, parent=$parent, repoInfo=$repoInfo, stream=$stream, timeout=$timeout, trialCount=$trialCount, additionalProperties=$additionalProperties}" } /** The dataset to use */ @@ -1741,14 +1819,13 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { datasetId != null -> visitor.visitDatasetId(datasetId) projectDatasetName != null -> visitor.visitProjectDatasetName(projectDatasetName) datasetRows != null -> visitor.visitDatasetRows(datasetRows) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1775,6 +1852,35 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitDatasetId(datasetId: DatasetId) = datasetId.validity() + + override fun visitProjectDatasetName(projectDatasetName: ProjectDatasetName) = + projectDatasetName.validity() + + override fun visitDatasetRows(datasetRows: DatasetRows) = datasetRows.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1839,20 +1945,31 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Data { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Data(datasetId = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Data(projectDatasetName = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Data(datasetRows = it, _json = json) - } - - return Data(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Data(datasetId = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Data(projectDatasetName = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Data(datasetRows = 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 -> Data(_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() + } } } @@ -1875,20 +1992,23 @@ private constructor( } /** Dataset id */ - @NoAutoDetect class DatasetId - @JsonCreator private constructor( - @JsonProperty("dataset_id") - @ExcludeMissing - private val datasetId: JsonField = JsonMissing.of(), - @JsonProperty("_internal_btql") - @ExcludeMissing - private val _internalBtql: JsonField<_InternalBtql> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val datasetId: JsonField, + private val _internalBtql: JsonField<_InternalBtql>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("dataset_id") + @ExcludeMissing + datasetId: JsonField = JsonMissing.of(), + @JsonProperty("_internal_btql") + @ExcludeMissing + _internalBtql: JsonField<_InternalBtql> = JsonMissing.of(), + ) : this(datasetId, _internalBtql, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -1901,7 +2021,7 @@ private constructor( * if the server responded with an unexpected value). */ fun _internalBtql(): Optional<_InternalBtql> = - Optional.ofNullable(_internalBtql.getNullable("_internal_btql")) + _internalBtql.getOptional("_internal_btql") /** * Returns the raw JSON value of [datasetId]. @@ -1923,21 +2043,15 @@ private constructor( @ExcludeMissing fun __internalBtql(): JsonField<_InternalBtql> = _internalBtql + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): DatasetId = apply { - if (validated) { - return@apply - } - - datasetId() - _internalBtql().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2035,32 +2149,52 @@ private constructor( DatasetId( checkRequired("datasetId", datasetId), _internalBtql, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): DatasetId = apply { + if (validated) { + return@apply + } + + datasetId() + _internalBtql().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (datasetId.asKnown().isPresent) 1 else 0) + + (_internalBtql.asKnown().getOrNull()?.validity() ?: 0) + class _InternalBtql @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): _InternalBtql = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -2111,6 +2245,36 @@ private constructor( fun build(): _InternalBtql = _InternalBtql(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): _InternalBtql = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2148,23 +2312,27 @@ private constructor( } /** Project and dataset name */ - @NoAutoDetect class ProjectDatasetName - @JsonCreator private constructor( - @JsonProperty("dataset_name") - @ExcludeMissing - private val datasetName: JsonField = JsonMissing.of(), - @JsonProperty("project_name") - @ExcludeMissing - private val projectName: JsonField = JsonMissing.of(), - @JsonProperty("_internal_btql") - @ExcludeMissing - private val _internalBtql: JsonField<_InternalBtql> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val datasetName: JsonField, + private val projectName: JsonField, + private val _internalBtql: JsonField<_InternalBtql>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("dataset_name") + @ExcludeMissing + datasetName: JsonField = JsonMissing.of(), + @JsonProperty("project_name") + @ExcludeMissing + projectName: JsonField = JsonMissing.of(), + @JsonProperty("_internal_btql") + @ExcludeMissing + _internalBtql: JsonField<_InternalBtql> = JsonMissing.of(), + ) : this(datasetName, projectName, _internalBtql, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -2184,7 +2352,7 @@ private constructor( * if the server responded with an unexpected value). */ fun _internalBtql(): Optional<_InternalBtql> = - Optional.ofNullable(_internalBtql.getNullable("_internal_btql")) + _internalBtql.getOptional("_internal_btql") /** * Returns the raw JSON value of [datasetName]. @@ -2216,22 +2384,15 @@ private constructor( @ExcludeMissing fun __internalBtql(): JsonField<_InternalBtql> = _internalBtql + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ProjectDatasetName = apply { - if (validated) { - return@apply - } - - datasetName() - projectName() - _internalBtql().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2349,32 +2510,54 @@ private constructor( checkRequired("datasetName", datasetName), checkRequired("projectName", projectName), _internalBtql, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): ProjectDatasetName = apply { + if (validated) { + return@apply + } + + datasetName() + projectName() + _internalBtql().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (datasetName.asKnown().isPresent) 1 else 0) + + (if (projectName.asKnown().isPresent) 1 else 0) + + (_internalBtql.asKnown().getOrNull()?.validity() ?: 0) + class _InternalBtql @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): _InternalBtql = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -2425,6 +2608,36 @@ private constructor( fun build(): _InternalBtql = _InternalBtql(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): _InternalBtql = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2462,17 +2675,19 @@ private constructor( } /** Dataset rows */ - @NoAutoDetect class DatasetRows - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("data") + @ExcludeMissing + data: JsonField> = JsonMissing.of() + ) : this(data, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -2487,20 +2702,15 @@ private constructor( */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField> = data + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): DatasetRows = apply { - if (validated) { - return@apply - } - - data() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2591,10 +2801,39 @@ private constructor( fun build(): DatasetRows = DatasetRows( checkRequired("data", data).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): DatasetRows = apply { + if (validated) { + return@apply + } + + data() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (data.asKnown().getOrNull()?.sumOf { (if (it == null) 0 else 1).toInt() } ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2678,8 +2917,8 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { functionId != null -> visitor.visitFunctionId(functionId) projectSlug != null -> visitor.visitProjectSlug(projectSlug) globalFunction != null -> visitor.visitGlobalFunction(globalFunction) @@ -2688,7 +2927,6 @@ private constructor( inlinePrompt != null -> visitor.visitInlinePrompt(inlinePrompt) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -2727,6 +2965,43 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitFunctionId(functionId: FunctionId) = functionId.validity() + + override fun visitProjectSlug(projectSlug: ProjectSlug) = projectSlug.validity() + + override fun visitGlobalFunction(globalFunction: GlobalFunction) = + globalFunction.validity() + + override fun visitPromptSessionId(promptSessionId: PromptSessionId) = + promptSessionId.validity() + + override fun visitInlineCode(inlineCode: InlineCode) = inlineCode.validity() + + override fun visitInlinePrompt(inlinePrompt: InlinePrompt) = + inlinePrompt.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2817,32 +3092,40 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Score { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Score(functionId = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Score(projectSlug = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Score(globalFunction = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Score(promptSessionId = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Score(inlineCode = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Score(inlinePrompt = it, _json = json) - } - - return Score(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Score(functionId = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Score(projectSlug = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Score(globalFunction = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Score(promptSessionId = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Score(inlineCode = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Score(inlinePrompt = 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 -> Score(_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() + } } } @@ -2867,20 +3150,23 @@ private constructor( } /** Function id */ - @NoAutoDetect class FunctionId - @JsonCreator private constructor( - @JsonProperty("function_id") - @ExcludeMissing - private val functionId: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val functionId: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("function_id") + @ExcludeMissing + functionId: JsonField = JsonMissing.of(), + @JsonProperty("version") + @ExcludeMissing + version: JsonField = JsonMissing.of(), + ) : this(functionId, version, mutableMapOf()) + /** * The ID of the function * @@ -2896,7 +3182,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun version(): Optional = Optional.ofNullable(version.getNullable("version")) + fun version(): Optional = version.getOptional("version") /** * Returns the raw JSON value of [functionId]. @@ -2915,21 +3201,15 @@ private constructor( */ @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): FunctionId = apply { - if (validated) { - return@apply - } - - functionId() - version() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3024,10 +3304,41 @@ private constructor( FunctionId( checkRequired("functionId", functionId), version, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): FunctionId = apply { + if (validated) { + return@apply + } + + functionId() + version() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (functionId.asKnown().isPresent) 1 else 0) + + (if (version.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3047,23 +3358,25 @@ private constructor( } /** Project name and slug */ - @NoAutoDetect class ProjectSlug - @JsonCreator private constructor( - @JsonProperty("project_name") - @ExcludeMissing - private val projectName: JsonField = JsonMissing.of(), - @JsonProperty("slug") - @ExcludeMissing - private val slug: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val projectName: JsonField, + private val slug: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("project_name") + @ExcludeMissing + projectName: JsonField = JsonMissing.of(), + @JsonProperty("slug") @ExcludeMissing slug: JsonField = JsonMissing.of(), + @JsonProperty("version") + @ExcludeMissing + version: JsonField = JsonMissing.of(), + ) : this(projectName, slug, version, mutableMapOf()) + /** * The name of the project containing the function * @@ -3088,7 +3401,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun version(): Optional = Optional.ofNullable(version.getNullable("version")) + fun version(): Optional = version.getOptional("version") /** * Returns the raw JSON value of [projectName]. @@ -3114,22 +3427,15 @@ private constructor( */ @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ProjectSlug = apply { - if (validated) { - return@apply - } - - projectName() - slug() - version() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3241,10 +3547,43 @@ private constructor( checkRequired("projectName", projectName), checkRequired("slug", slug), version, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): ProjectSlug = apply { + if (validated) { + return@apply + } + + projectName() + slug() + version() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (projectName.asKnown().isPresent) 1 else 0) + + (if (slug.asKnown().isPresent) 1 else 0) + + (if (version.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3264,17 +3603,19 @@ private constructor( } /** Global function name */ - @NoAutoDetect class GlobalFunction - @JsonCreator private constructor( - @JsonProperty("global_function") - @ExcludeMissing - private val globalFunction: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val globalFunction: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("global_function") + @ExcludeMissing + globalFunction: JsonField = JsonMissing.of() + ) : this(globalFunction, mutableMapOf()) + /** * The name of the global function. Currently, the global namespace includes the * functions in autoevals @@ -3295,20 +3636,15 @@ private constructor( @ExcludeMissing fun _globalFunction(): JsonField = globalFunction + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): GlobalFunction = apply { - if (validated) { - return@apply - } - - globalFunction() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3392,10 +3728,38 @@ private constructor( fun build(): GlobalFunction = GlobalFunction( checkRequired("globalFunction", globalFunction), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): GlobalFunction = apply { + if (validated) { + return@apply + } + + globalFunction() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (globalFunction.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3415,23 +3779,27 @@ private constructor( } /** Prompt session id */ - @NoAutoDetect class PromptSessionId - @JsonCreator private constructor( - @JsonProperty("prompt_session_function_id") - @ExcludeMissing - private val promptSessionFunctionId: JsonField = JsonMissing.of(), - @JsonProperty("prompt_session_id") - @ExcludeMissing - private val promptSessionId: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val promptSessionFunctionId: JsonField, + private val promptSessionId: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("prompt_session_function_id") + @ExcludeMissing + promptSessionFunctionId: JsonField = JsonMissing.of(), + @JsonProperty("prompt_session_id") + @ExcludeMissing + promptSessionId: JsonField = JsonMissing.of(), + @JsonProperty("version") + @ExcludeMissing + version: JsonField = JsonMissing.of(), + ) : this(promptSessionFunctionId, promptSessionId, version, mutableMapOf()) + /** * The ID of the function in the prompt session * @@ -3457,7 +3825,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun version(): Optional = Optional.ofNullable(version.getNullable("version")) + fun version(): Optional = version.getOptional("version") /** * Returns the raw JSON value of [promptSessionFunctionId]. @@ -3486,22 +3854,15 @@ private constructor( */ @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PromptSessionId = apply { - if (validated) { - return@apply - } - - promptSessionFunctionId() - promptSessionId() - version() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3617,10 +3978,43 @@ private constructor( checkRequired("promptSessionFunctionId", promptSessionFunctionId), checkRequired("promptSessionId", promptSessionId), version, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): PromptSessionId = apply { + if (validated) { + return@apply + } + + promptSessionFunctionId() + promptSessionId() + version() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (promptSessionFunctionId.asKnown().isPresent) 1 else 0) + + (if (promptSessionId.asKnown().isPresent) 1 else 0) + + (if (version.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3640,23 +4034,23 @@ private constructor( } /** Inline code function */ - @NoAutoDetect class InlineCode - @JsonCreator private constructor( - @JsonProperty("code") - @ExcludeMissing - private val code: JsonField = JsonMissing.of(), - @JsonProperty("inline_context") - @ExcludeMissing - private val inlineContext: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val code: JsonField, + private val inlineContext: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("code") @ExcludeMissing code: JsonField = JsonMissing.of(), + @JsonProperty("inline_context") + @ExcludeMissing + inlineContext: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(code, inlineContext, name, mutableMapOf()) + /** * The inline code to execute * @@ -3679,7 +4073,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun name(): Optional = name.getOptional("name") /** * Returns the raw JSON value of [code]. @@ -3705,22 +4099,15 @@ private constructor( */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): InlineCode = apply { - if (validated) { - return@apply - } - - code() - inlineContext().validate() - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3835,24 +4222,60 @@ private constructor( checkRequired("code", code), checkRequired("inlineContext", inlineContext), name, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): InlineCode = apply { + if (validated) { + return@apply + } + + code() + inlineContext().validate() + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (code.asKnown().isPresent) 1 else 0) + + (inlineContext.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + class InlineContext - @JsonCreator private constructor( - @JsonProperty("runtime") - @ExcludeMissing - private val runtime: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val runtime: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("runtime") + @ExcludeMissing + runtime: JsonField = JsonMissing.of(), + @JsonProperty("version") + @ExcludeMissing + version: JsonField = JsonMissing.of(), + ) : this(runtime, version, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type * or is unexpectedly missing or null (e.g. if the server responded with an @@ -3885,21 +4308,15 @@ private constructor( */ @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): InlineContext = apply { - if (validated) { - return@apply - } - - runtime() - version() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3992,10 +4409,41 @@ private constructor( InlineContext( checkRequired("runtime", runtime), checkRequired("version", version), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): InlineContext = apply { + if (validated) { + return@apply + } + + runtime().validate() + version() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (runtime.asKnown().getOrNull()?.validity() ?: 0) + + (if (version.asKnown().isPresent) 1 else 0) + class Runtime @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -4089,6 +4537,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Runtime = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -4139,28 +4615,28 @@ private constructor( } /** Inline prompt definition */ - @NoAutoDetect class InlinePrompt - @JsonCreator private constructor( - @JsonProperty("inline_prompt") - @ExcludeMissing - private val inlinePrompt: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val inlinePrompt: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("inline_prompt") + @ExcludeMissing + inlinePrompt: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(inlinePrompt, name, mutableMapOf()) + /** * The prompt, model, and its parameters * * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun inlinePrompt(): Optional = - Optional.ofNullable(inlinePrompt.getNullable("inline_prompt")) + fun inlinePrompt(): Optional = inlinePrompt.getOptional("inline_prompt") /** * The name of the inline prompt @@ -4168,7 +4644,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun name(): Optional = name.getOptional("name") /** * Returns the raw JSON value of [inlinePrompt]. @@ -4187,21 +4663,15 @@ private constructor( */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): InlinePrompt = apply { - if (validated) { - return@apply - } - - inlinePrompt().ifPresent { it.validate() } - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -4304,10 +4774,41 @@ private constructor( InlinePrompt( checkRequired("inlinePrompt", inlinePrompt), name, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): InlinePrompt = apply { + if (validated) { + return@apply + } + + inlinePrompt().ifPresent { it.validate() } + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (inlinePrompt.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -4391,8 +4892,8 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { functionId != null -> visitor.visitFunctionId(functionId) projectSlug != null -> visitor.visitProjectSlug(projectSlug) globalFunction != null -> visitor.visitGlobalFunction(globalFunction) @@ -4401,7 +4902,6 @@ private constructor( inlinePrompt != null -> visitor.visitInlinePrompt(inlinePrompt) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -4440,6 +4940,43 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitFunctionId(functionId: FunctionId) = functionId.validity() + + override fun visitProjectSlug(projectSlug: ProjectSlug) = projectSlug.validity() + + override fun visitGlobalFunction(globalFunction: GlobalFunction) = + globalFunction.validity() + + override fun visitPromptSessionId(promptSessionId: PromptSessionId) = + promptSessionId.validity() + + override fun visitInlineCode(inlineCode: InlineCode) = inlineCode.validity() + + override fun visitInlinePrompt(inlinePrompt: InlinePrompt) = + inlinePrompt.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -4528,32 +5065,40 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Task { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Task(functionId = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Task(projectSlug = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Task(globalFunction = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Task(promptSessionId = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Task(inlineCode = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Task(inlinePrompt = it, _json = json) - } - - return Task(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Task(functionId = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Task(projectSlug = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Task(globalFunction = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Task(promptSessionId = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Task(inlineCode = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Task(inlinePrompt = 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 -> Task(_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() + } } } @@ -4578,20 +5123,23 @@ private constructor( } /** Function id */ - @NoAutoDetect class FunctionId - @JsonCreator private constructor( - @JsonProperty("function_id") - @ExcludeMissing - private val functionId: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val functionId: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("function_id") + @ExcludeMissing + functionId: JsonField = JsonMissing.of(), + @JsonProperty("version") + @ExcludeMissing + version: JsonField = JsonMissing.of(), + ) : this(functionId, version, mutableMapOf()) + /** * The ID of the function * @@ -4607,7 +5155,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun version(): Optional = Optional.ofNullable(version.getNullable("version")) + fun version(): Optional = version.getOptional("version") /** * Returns the raw JSON value of [functionId]. @@ -4626,21 +5174,15 @@ private constructor( */ @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): FunctionId = apply { - if (validated) { - return@apply - } - - functionId() - version() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -4735,10 +5277,41 @@ private constructor( FunctionId( checkRequired("functionId", functionId), version, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): FunctionId = apply { + if (validated) { + return@apply + } + + functionId() + version() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (functionId.asKnown().isPresent) 1 else 0) + + (if (version.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -4758,23 +5331,25 @@ private constructor( } /** Project name and slug */ - @NoAutoDetect class ProjectSlug - @JsonCreator private constructor( - @JsonProperty("project_name") - @ExcludeMissing - private val projectName: JsonField = JsonMissing.of(), - @JsonProperty("slug") - @ExcludeMissing - private val slug: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val projectName: JsonField, + private val slug: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("project_name") + @ExcludeMissing + projectName: JsonField = JsonMissing.of(), + @JsonProperty("slug") @ExcludeMissing slug: JsonField = JsonMissing.of(), + @JsonProperty("version") + @ExcludeMissing + version: JsonField = JsonMissing.of(), + ) : this(projectName, slug, version, mutableMapOf()) + /** * The name of the project containing the function * @@ -4799,7 +5374,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun version(): Optional = Optional.ofNullable(version.getNullable("version")) + fun version(): Optional = version.getOptional("version") /** * Returns the raw JSON value of [projectName]. @@ -4825,22 +5400,15 @@ private constructor( */ @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ProjectSlug = apply { - if (validated) { - return@apply - } - - projectName() - slug() - version() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -4952,10 +5520,43 @@ private constructor( checkRequired("projectName", projectName), checkRequired("slug", slug), version, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): ProjectSlug = apply { + if (validated) { + return@apply + } + + projectName() + slug() + version() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (projectName.asKnown().isPresent) 1 else 0) + + (if (slug.asKnown().isPresent) 1 else 0) + + (if (version.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -4975,17 +5576,19 @@ private constructor( } /** Global function name */ - @NoAutoDetect class GlobalFunction - @JsonCreator private constructor( - @JsonProperty("global_function") - @ExcludeMissing - private val globalFunction: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val globalFunction: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("global_function") + @ExcludeMissing + globalFunction: JsonField = JsonMissing.of() + ) : this(globalFunction, mutableMapOf()) + /** * The name of the global function. Currently, the global namespace includes the * functions in autoevals @@ -5006,20 +5609,15 @@ private constructor( @ExcludeMissing fun _globalFunction(): JsonField = globalFunction + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): GlobalFunction = apply { - if (validated) { - return@apply - } - - globalFunction() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -5103,10 +5701,38 @@ private constructor( fun build(): GlobalFunction = GlobalFunction( checkRequired("globalFunction", globalFunction), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): GlobalFunction = apply { + if (validated) { + return@apply + } + + globalFunction() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (globalFunction.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -5126,23 +5752,27 @@ private constructor( } /** Prompt session id */ - @NoAutoDetect class PromptSessionId - @JsonCreator private constructor( - @JsonProperty("prompt_session_function_id") - @ExcludeMissing - private val promptSessionFunctionId: JsonField = JsonMissing.of(), - @JsonProperty("prompt_session_id") - @ExcludeMissing - private val promptSessionId: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val promptSessionFunctionId: JsonField, + private val promptSessionId: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("prompt_session_function_id") + @ExcludeMissing + promptSessionFunctionId: JsonField = JsonMissing.of(), + @JsonProperty("prompt_session_id") + @ExcludeMissing + promptSessionId: JsonField = JsonMissing.of(), + @JsonProperty("version") + @ExcludeMissing + version: JsonField = JsonMissing.of(), + ) : this(promptSessionFunctionId, promptSessionId, version, mutableMapOf()) + /** * The ID of the function in the prompt session * @@ -5168,7 +5798,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun version(): Optional = Optional.ofNullable(version.getNullable("version")) + fun version(): Optional = version.getOptional("version") /** * Returns the raw JSON value of [promptSessionFunctionId]. @@ -5197,22 +5827,15 @@ private constructor( */ @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PromptSessionId = apply { - if (validated) { - return@apply - } - - promptSessionFunctionId() - promptSessionId() - version() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -5328,10 +5951,43 @@ private constructor( checkRequired("promptSessionFunctionId", promptSessionFunctionId), checkRequired("promptSessionId", promptSessionId), version, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): PromptSessionId = apply { + if (validated) { + return@apply + } + + promptSessionFunctionId() + promptSessionId() + version() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (promptSessionFunctionId.asKnown().isPresent) 1 else 0) + + (if (promptSessionId.asKnown().isPresent) 1 else 0) + + (if (version.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -5351,23 +6007,23 @@ private constructor( } /** Inline code function */ - @NoAutoDetect class InlineCode - @JsonCreator private constructor( - @JsonProperty("code") - @ExcludeMissing - private val code: JsonField = JsonMissing.of(), - @JsonProperty("inline_context") - @ExcludeMissing - private val inlineContext: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val code: JsonField, + private val inlineContext: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("code") @ExcludeMissing code: JsonField = JsonMissing.of(), + @JsonProperty("inline_context") + @ExcludeMissing + inlineContext: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(code, inlineContext, name, mutableMapOf()) + /** * The inline code to execute * @@ -5390,7 +6046,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun name(): Optional = name.getOptional("name") /** * Returns the raw JSON value of [code]. @@ -5416,22 +6072,15 @@ private constructor( */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): InlineCode = apply { - if (validated) { - return@apply - } - - code() - inlineContext().validate() - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -5546,24 +6195,60 @@ private constructor( checkRequired("code", code), checkRequired("inlineContext", inlineContext), name, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): InlineCode = apply { + if (validated) { + return@apply + } + + code() + inlineContext().validate() + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (code.asKnown().isPresent) 1 else 0) + + (inlineContext.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + class InlineContext - @JsonCreator private constructor( - @JsonProperty("runtime") - @ExcludeMissing - private val runtime: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val runtime: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("runtime") + @ExcludeMissing + runtime: JsonField = JsonMissing.of(), + @JsonProperty("version") + @ExcludeMissing + version: JsonField = JsonMissing.of(), + ) : this(runtime, version, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type * or is unexpectedly missing or null (e.g. if the server responded with an @@ -5596,21 +6281,15 @@ private constructor( */ @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): InlineContext = apply { - if (validated) { - return@apply - } - - runtime() - version() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -5703,10 +6382,41 @@ private constructor( InlineContext( checkRequired("runtime", runtime), checkRequired("version", version), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): InlineContext = apply { + if (validated) { + return@apply + } + + runtime().validate() + version() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (runtime.asKnown().getOrNull()?.validity() ?: 0) + + (if (version.asKnown().isPresent) 1 else 0) + class Runtime @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -5800,6 +6510,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Runtime = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -5850,28 +6588,28 @@ private constructor( } /** Inline prompt definition */ - @NoAutoDetect class InlinePrompt - @JsonCreator private constructor( - @JsonProperty("inline_prompt") - @ExcludeMissing - private val inlinePrompt: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val inlinePrompt: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("inline_prompt") + @ExcludeMissing + inlinePrompt: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(inlinePrompt, name, mutableMapOf()) + /** * The prompt, model, and its parameters * * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun inlinePrompt(): Optional = - Optional.ofNullable(inlinePrompt.getNullable("inline_prompt")) + fun inlinePrompt(): Optional = inlinePrompt.getOptional("inline_prompt") /** * The name of the inline prompt @@ -5879,7 +6617,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun name(): Optional = name.getOptional("name") /** * Returns the raw JSON value of [inlinePrompt]. @@ -5898,21 +6636,15 @@ private constructor( */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): InlinePrompt = apply { - if (validated) { - return@apply - } - - inlinePrompt().ifPresent { it.validate() } - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -6015,10 +6747,41 @@ private constructor( InlinePrompt( checkRequired("inlinePrompt", inlinePrompt), name, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): InlinePrompt = apply { + if (validated) { + return@apply + } + + inlinePrompt().ifPresent { it.validate() } + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (inlinePrompt.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -6042,20 +6805,21 @@ private constructor( * Optional settings for collecting git metadata. By default, will collect all git metadata * fields allowed in org-level settings. */ - @NoAutoDetect class GitMetadataSettings - @JsonCreator private constructor( - @JsonProperty("collect") - @ExcludeMissing - private val collect: JsonField = JsonMissing.of(), - @JsonProperty("fields") - @ExcludeMissing - private val fields: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val collect: JsonField, + private val fields: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("collect") @ExcludeMissing collect: JsonField = JsonMissing.of(), + @JsonProperty("fields") + @ExcludeMissing + fields: JsonField> = JsonMissing.of(), + ) : this(collect, fields, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected value). @@ -6066,7 +6830,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun fields(): Optional> = Optional.ofNullable(fields.getNullable("fields")) + fun fields(): Optional> = fields.getOptional("fields") /** * Returns the raw JSON value of [collect]. @@ -6082,21 +6846,15 @@ private constructor( */ @JsonProperty("fields") @ExcludeMissing fun _fields(): JsonField> = fields + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): GitMetadataSettings = apply { - if (validated) { - return@apply - } - - collect() - fields() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -6198,10 +6956,41 @@ private constructor( GitMetadataSettings( checkRequired("collect", collect), (fields ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): GitMetadataSettings = apply { + if (validated) { + return@apply + } + + collect().validate() + fields().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (collect.asKnown().getOrNull()?.validity() ?: 0) + + (fields.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + class Collect @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -6298,6 +7087,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Collect = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -6442,6 +7258,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Field = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -6477,28 +7320,17 @@ private constructor( * Optional experiment-level metadata to store about the evaluation. You can later use this to * slice & dice across experiments. */ - @NoAutoDetect class Metadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -6544,6 +7376,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -6589,13 +7449,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { spanParentStruct != null -> visitor.visitSpanParentStruct(spanParentStruct) string != null -> visitor.visitString(string) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -6616,6 +7475,33 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitSpanParentStruct(spanParentStruct: SpanParentStruct) = + spanParentStruct.validity() + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -6674,15 +7560,28 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Parent { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Parent(spanParentStruct = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef())?.let { - return Parent(string = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Parent(spanParentStruct = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Parent(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 array). + 0 -> Parent(_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 Parent(_json = json) } } @@ -6703,26 +7602,31 @@ private constructor( } /** Span parent properties */ - @NoAutoDetect class SpanParentStruct - @JsonCreator private constructor( - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("propagated_event") - @ExcludeMissing - private val propagatedEvent: JsonField = JsonMissing.of(), - @JsonProperty("row_ids") - @ExcludeMissing - private val rowIds: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val objectId: JsonField, + private val objectType: JsonField, + private val propagatedEvent: JsonField, + private val rowIds: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("object_id") + @ExcludeMissing + objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("propagated_event") + @ExcludeMissing + propagatedEvent: JsonField = JsonMissing.of(), + @JsonProperty("row_ids") + @ExcludeMissing + rowIds: JsonField = JsonMissing.of(), + ) : this(objectId, objectType, propagatedEvent, rowIds, mutableMapOf()) + /** * The id of the container object you are logging to * @@ -6746,7 +7650,7 @@ private constructor( * if the server responded with an unexpected value). */ fun propagatedEvent(): Optional = - Optional.ofNullable(propagatedEvent.getNullable("propagated_event")) + propagatedEvent.getOptional("propagated_event") /** * Identifiers for the row to to log a subspan under @@ -6754,7 +7658,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun rowIds(): Optional = Optional.ofNullable(rowIds.getNullable("row_ids")) + fun rowIds(): Optional = rowIds.getOptional("row_ids") /** * Returns the raw JSON value of [objectId]. @@ -6791,23 +7695,15 @@ private constructor( */ @JsonProperty("row_ids") @ExcludeMissing fun _rowIds(): JsonField = rowIds + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SpanParentStruct = apply { - if (validated) { - return@apply - } - - objectId() - objectType() - propagatedEvent().ifPresent { it.validate() } - rowIds().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -6945,10 +7841,45 @@ private constructor( checkRequired("objectType", objectType), propagatedEvent, rowIds, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): SpanParentStruct = apply { + if (validated) { + return@apply + } + + objectId() + objectType().validate() + propagatedEvent().ifPresent { it.validate() } + rowIds().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (propagatedEvent.asKnown().getOrNull()?.validity() ?: 0) + + (rowIds.asKnown().getOrNull()?.validity() ?: 0) + class ObjectType @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -7047,6 +7978,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ObjectType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -7061,28 +8019,17 @@ private constructor( } /** Include these properties in every span created under this parent */ - @NoAutoDetect class PropagatedEvent @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): PropagatedEvent = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -7134,6 +8081,36 @@ private constructor( PropagatedEvent(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): PropagatedEvent = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -7153,23 +8130,25 @@ private constructor( } /** Identifiers for the row to to log a subspan under */ - @NoAutoDetect class RowIds - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("root_span_id") - @ExcludeMissing - private val rootSpanId: JsonField = JsonMissing.of(), - @JsonProperty("span_id") - @ExcludeMissing - private val spanId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val rootSpanId: JsonField, + private val spanId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("root_span_id") + @ExcludeMissing + rootSpanId: JsonField = JsonMissing.of(), + @JsonProperty("span_id") + @ExcludeMissing + spanId: JsonField = JsonMissing.of(), + ) : this(id, rootSpanId, spanId, mutableMapOf()) + /** * The id of the row * @@ -7222,22 +8201,15 @@ private constructor( */ @JsonProperty("span_id") @ExcludeMissing fun _spanId(): JsonField = spanId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): RowIds = apply { - if (validated) { - return@apply - } - - id() - rootSpanId() - spanId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -7351,10 +8323,43 @@ private constructor( checkRequired("id", id), checkRequired("rootSpanId", rootSpanId), checkRequired("spanId", spanId), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): RowIds = apply { + if (validated) { + return@apply + } + + id() + rootSpanId() + spanId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (rootSpanId.asKnown().isPresent) 1 else 0) + + (if (spanId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Experiment.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Experiment.kt index 78d87c27..e756f680 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Experiment.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Experiment.kt @@ -6,9 +6,7 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -16,55 +14,74 @@ import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class Experiment -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("public") - @ExcludeMissing - private val public_: JsonField = JsonMissing.of(), - @JsonProperty("base_exp_id") - @ExcludeMissing - private val baseExpId: JsonField = JsonMissing.of(), - @JsonProperty("commit") - @ExcludeMissing - private val commit: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("dataset_id") - @ExcludeMissing - private val datasetId: JsonField = JsonMissing.of(), - @JsonProperty("dataset_version") - @ExcludeMissing - private val datasetVersion: JsonField = JsonMissing.of(), - @JsonProperty("deleted_at") - @ExcludeMissing - private val deletedAt: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("repo_info") - @ExcludeMissing - private val repoInfo: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val name: JsonField, + private val projectId: JsonField, + private val public_: JsonField, + private val baseExpId: JsonField, + private val commit: JsonField, + private val created: JsonField, + private val datasetId: JsonField, + private val datasetVersion: JsonField, + private val deletedAt: JsonField, + private val description: JsonField, + private val metadata: JsonField, + private val repoInfo: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") @ExcludeMissing projectId: JsonField = JsonMissing.of(), + @JsonProperty("public") @ExcludeMissing public_: JsonField = JsonMissing.of(), + @JsonProperty("base_exp_id") + @ExcludeMissing + baseExpId: JsonField = JsonMissing.of(), + @JsonProperty("commit") @ExcludeMissing commit: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("dataset_id") @ExcludeMissing datasetId: JsonField = JsonMissing.of(), + @JsonProperty("dataset_version") + @ExcludeMissing + datasetVersion: JsonField = JsonMissing.of(), + @JsonProperty("deleted_at") + @ExcludeMissing + deletedAt: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("repo_info") @ExcludeMissing repoInfo: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this( + id, + name, + projectId, + public_, + baseExpId, + commit, + created, + datasetId, + datasetVersion, + deletedAt, + description, + metadata, + repoInfo, + userId, + mutableMapOf(), + ) + /** * Unique identifier for the experiment * @@ -104,7 +121,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun baseExpId(): Optional = Optional.ofNullable(baseExpId.getNullable("base_exp_id")) + fun baseExpId(): Optional = baseExpId.getOptional("base_exp_id") /** * Commit, taken directly from `repo_info.commit` @@ -112,7 +129,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun commit(): Optional = Optional.ofNullable(commit.getNullable("commit")) + fun commit(): Optional = commit.getOptional("commit") /** * Date of experiment creation @@ -120,7 +137,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Identifier of the linked dataset, or null if the experiment is not linked to a dataset @@ -128,7 +145,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun datasetId(): Optional = Optional.ofNullable(datasetId.getNullable("dataset_id")) + fun datasetId(): Optional = datasetId.getOptional("dataset_id") /** * Version number of the linked dataset the experiment was run against. This can be used to @@ -137,8 +154,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun datasetVersion(): Optional = - Optional.ofNullable(datasetVersion.getNullable("dataset_version")) + fun datasetVersion(): Optional = datasetVersion.getOptional("dataset_version") /** * Date of experiment deletion, or null if the experiment is still active @@ -146,8 +162,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun deletedAt(): Optional = - Optional.ofNullable(deletedAt.getNullable("deleted_at")) + fun deletedAt(): Optional = deletedAt.getOptional("deleted_at") /** * Textual description of the experiment @@ -155,8 +170,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun description(): Optional = description.getOptional("description") /** * User-controlled metadata about the experiment @@ -164,7 +178,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** * Metadata about the state of the repo when the experiment was created @@ -172,7 +186,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun repoInfo(): Optional = Optional.ofNullable(repoInfo.getNullable("repo_info")) + fun repoInfo(): Optional = repoInfo.getOptional("repo_info") /** * Identifies the user who created the experiment @@ -180,7 +194,7 @@ private constructor( * @throws BraintrustInvalidDataException 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 [id]. @@ -284,33 +298,15 @@ private constructor( */ @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 = additionalProperties - - private var validated: Boolean = false - - fun validate(): Experiment = apply { - if (validated) { - return@apply - } - - id() - name() - projectId() - public_() - baseExpId() - commit() - created() - datasetId() - datasetVersion() - deletedAt() - description() - metadata().ifPresent { it.validate() } - repoInfo().ifPresent { it.validate() } - userId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -623,33 +619,76 @@ private constructor( metadata, repoInfo, userId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Experiment = apply { + if (validated) { + return@apply + } + + id() + name() + projectId() + public_() + baseExpId() + commit() + created() + datasetId() + datasetVersion() + deletedAt() + description() + metadata().ifPresent { it.validate() } + repoInfo().ifPresent { it.validate() } + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (public_.asKnown().isPresent) 1 else 0) + + (if (baseExpId.asKnown().isPresent) 1 else 0) + + (if (commit.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (datasetId.asKnown().isPresent) 1 else 0) + + (if (datasetVersion.asKnown().isPresent) 1 else 0) + + (if (deletedAt.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (repoInfo.asKnown().getOrNull()?.validity() ?: 0) + + (if (userId.asKnown().isPresent) 1 else 0) + /** User-controlled metadata about the experiment */ - @NoAutoDetect class Metadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -695,6 +734,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentCreateParams.kt index bee4ab93..f1387ce7 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentCreateParams.kt @@ -6,18 +6,17 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -193,891 +192,941 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun toBuilder() = Builder().from(this) - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("base_exp_id") - @ExcludeMissing - private val baseExpId: JsonField = JsonMissing.of(), - @JsonProperty("dataset_id") - @ExcludeMissing - private val datasetId: JsonField = JsonMissing.of(), - @JsonProperty("dataset_version") - @ExcludeMissing - private val datasetVersion: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("ensure_new") - @ExcludeMissing - private val ensureNew: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("public") - @ExcludeMissing - private val public_: JsonField = JsonMissing.of(), - @JsonProperty("repo_info") - @ExcludeMissing - private val repoInfo: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + companion object { /** - * Unique identifier for the project that the experiment belongs under + * Returns a mutable builder for constructing an instance of [ExperimentCreateParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .projectId() + * ``` */ - fun projectId(): String = projectId.getRequired("project_id") + @JvmStatic fun builder() = Builder() + } - /** - * Id of default base experiment to compare against when viewing this experiment - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun baseExpId(): Optional = - Optional.ofNullable(baseExpId.getNullable("base_exp_id")) + /** A builder for [ExperimentCreateParams]. */ + class Builder internal constructor() { - /** - * Identifier of the linked dataset, or null if the experiment is not linked to a dataset - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun datasetId(): Optional = Optional.ofNullable(datasetId.getNullable("dataset_id")) + 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(experimentCreateParams: ExperimentCreateParams) = apply { + body = experimentCreateParams.body.toBuilder() + additionalHeaders = experimentCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = experimentCreateParams.additionalQueryParams.toBuilder() + } /** - * Version number of the linked dataset the experiment was run against. This can be used to - * reproduce the experiment after the dataset has been modified. + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [projectId] + * - [baseExpId] + * - [datasetId] + * - [datasetVersion] + * - [description] + * - etc. */ - fun datasetVersion(): Optional = - Optional.ofNullable(datasetVersion.getNullable("dataset_version")) + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Unique identifier for the project that the experiment belongs under */ + fun projectId(projectId: String) = apply { body.projectId(projectId) } /** - * Textual description of the experiment + * Sets [Builder.projectId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } + + /** Id of default base experiment to compare against when viewing this experiment */ + fun baseExpId(baseExpId: String?) = apply { body.baseExpId(baseExpId) } + + /** Alias for calling [Builder.baseExpId] with `baseExpId.orElse(null)`. */ + fun baseExpId(baseExpId: Optional) = baseExpId(baseExpId.getOrNull()) /** - * Normally, creating an experiment with the same name as an existing experiment will return - * the existing one un-modified. But if `ensure_new` is true, registration will generate a - * new experiment with a unique name in case of a conflict. + * Sets [Builder.baseExpId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.baseExpId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun ensureNew(): Optional = - Optional.ofNullable(ensureNew.getNullable("ensure_new")) + fun baseExpId(baseExpId: JsonField) = apply { body.baseExpId(baseExpId) } /** - * User-controlled metadata about the experiment - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * Identifier of the linked dataset, or null if the experiment is not linked to a dataset */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun datasetId(datasetId: String?) = apply { body.datasetId(datasetId) } + + /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ + fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) /** - * Name of the experiment. Within a project, experiment names are unique + * Sets [Builder.datasetId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.datasetId] 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(): Optional = Optional.ofNullable(name.getNullable("name")) + fun datasetId(datasetId: JsonField) = apply { body.datasetId(datasetId) } /** - * Whether or not the experiment is public. Public experiments can be viewed by anybody - * inside or outside the organization - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * Version number of the linked dataset the experiment was run against. This can be used to + * reproduce the experiment after the dataset has been modified. */ - fun public_(): Optional = Optional.ofNullable(public_.getNullable("public")) + fun datasetVersion(datasetVersion: String?) = apply { body.datasetVersion(datasetVersion) } + + /** Alias for calling [Builder.datasetVersion] with `datasetVersion.orElse(null)`. */ + fun datasetVersion(datasetVersion: Optional) = + datasetVersion(datasetVersion.getOrNull()) /** - * Metadata about the state of the repo when the experiment was created + * Sets [Builder.datasetVersion] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.datasetVersion] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun repoInfo(): Optional = Optional.ofNullable(repoInfo.getNullable("repo_info")) + fun datasetVersion(datasetVersion: JsonField) = apply { + body.datasetVersion(datasetVersion) + } + + /** Textual description of the experiment */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) /** - * Returns the raw JSON value of [projectId]. + * Sets [Builder.description] to an arbitrary JSON value. * - * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId + fun description(description: JsonField) = apply { body.description(description) } /** - * Returns the raw JSON value of [baseExpId]. - * - * Unlike [baseExpId], this method doesn't throw if the JSON field has an unexpected type. + * Normally, creating an experiment with the same name as an existing experiment will return + * the existing one un-modified. But if `ensure_new` is true, registration will generate a + * new experiment with a unique name in case of a conflict. */ - @JsonProperty("base_exp_id") @ExcludeMissing fun _baseExpId(): JsonField = baseExpId + fun ensureNew(ensureNew: Boolean?) = apply { body.ensureNew(ensureNew) } /** - * Returns the raw JSON value of [datasetId]. + * Alias for [Builder.ensureNew]. * - * Unlike [datasetId], this method doesn't throw if the JSON field has an unexpected type. + * This unboxed primitive overload exists for backwards compatibility. */ - @JsonProperty("dataset_id") @ExcludeMissing fun _datasetId(): JsonField = datasetId + fun ensureNew(ensureNew: Boolean) = ensureNew(ensureNew as Boolean?) + + /** Alias for calling [Builder.ensureNew] with `ensureNew.orElse(null)`. */ + fun ensureNew(ensureNew: Optional) = ensureNew(ensureNew.getOrNull()) /** - * Returns the raw JSON value of [datasetVersion]. + * Sets [Builder.ensureNew] to an arbitrary JSON value. * - * Unlike [datasetVersion], this method doesn't throw if the JSON field has an unexpected - * type. + * You should usually call [Builder.ensureNew] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("dataset_version") - @ExcludeMissing - fun _datasetVersion(): JsonField = datasetVersion + fun ensureNew(ensureNew: JsonField) = apply { body.ensureNew(ensureNew) } + + /** User-controlled metadata about the experiment */ + fun metadata(metadata: Metadata?) = apply { body.metadata(metadata) } + + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) /** - * Returns the raw JSON value of [description]. + * Sets [Builder.metadata] to an arbitrary JSON value. * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description + fun metadata(metadata: JsonField) = apply { body.metadata(metadata) } + + /** Name of the experiment. Within a project, experiment names are unique */ + fun name(name: String?) = apply { body.name(name) } + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) /** - * Returns the raw JSON value of [ensureNew]. + * Sets [Builder.name] to an arbitrary JSON value. * - * Unlike [ensureNew], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("ensure_new") @ExcludeMissing fun _ensureNew(): JsonField = ensureNew + fun name(name: JsonField) = apply { body.name(name) } /** - * Returns the raw JSON value of [metadata]. - * - * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + * Whether or not the experiment is public. Public experiments can be viewed by anybody + * inside or outside the organization */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + fun public_(public_: Boolean?) = apply { body.public_(public_) } /** - * Returns the raw JSON value of [name]. + * Alias for [Builder.public_]. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * This unboxed primitive overload exists for backwards compatibility. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun public_(public_: Boolean) = public_(public_ as Boolean?) + + /** Alias for calling [Builder.public_] with `public_.orElse(null)`. */ + fun public_(public_: Optional) = public_(public_.getOrNull()) /** - * Returns the raw JSON value of [public_]. + * Sets [Builder.public_] to an arbitrary JSON value. * - * Unlike [public_], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.public_] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("public") @ExcludeMissing fun _public_(): JsonField = public_ + fun public_(public_: JsonField) = apply { body.public_(public_) } + + /** Metadata about the state of the repo when the experiment was created */ + fun repoInfo(repoInfo: RepoInfo?) = apply { body.repoInfo(repoInfo) } + + /** Alias for calling [Builder.repoInfo] with `repoInfo.orElse(null)`. */ + fun repoInfo(repoInfo: Optional) = repoInfo(repoInfo.getOrNull()) /** - * Returns the raw JSON value of [repoInfo]. + * Sets [Builder.repoInfo] to an arbitrary JSON value. * - * Unlike [repoInfo], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.repoInfo] with a well-typed [RepoInfo] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("repo_info") @ExcludeMissing fun _repoInfo(): JsonField = repoInfo + fun repoInfo(repoInfo: JsonField) = apply { body.repoInfo(repoInfo) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var validated: Boolean = false + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - fun validate(): Body = apply { - if (validated) { - return@apply + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - projectId() - baseExpId() - datasetId() - datasetVersion() - description() - ensureNew() - metadata().ifPresent { it.validate() } - name() - public_() - repoInfo().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .projectId() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var projectId: JsonField? = null - private var baseExpId: JsonField = JsonMissing.of() - private var datasetId: JsonField = JsonMissing.of() - private var datasetVersion: JsonField = JsonMissing.of() - private var description: JsonField = JsonMissing.of() - private var ensureNew: JsonField = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var public_: JsonField = JsonMissing.of() - private var repoInfo: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - projectId = body.projectId - baseExpId = body.baseExpId - datasetId = body.datasetId - datasetVersion = body.datasetVersion - description = body.description - ensureNew = body.ensureNew - metadata = body.metadata - name = body.name - public_ = body.public_ - repoInfo = body.repoInfo - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** Unique identifier for the project that the experiment belongs under */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - - /** - * Sets [Builder.projectId] to an arbitrary JSON value. - * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } - - /** Id of default base experiment to compare against when viewing this experiment */ - fun baseExpId(baseExpId: String?) = baseExpId(JsonField.ofNullable(baseExpId)) - - /** Alias for calling [Builder.baseExpId] with `baseExpId.orElse(null)`. */ - fun baseExpId(baseExpId: Optional) = baseExpId(baseExpId.getOrNull()) - - /** - * Sets [Builder.baseExpId] to an arbitrary JSON value. - * - * You should usually call [Builder.baseExpId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun baseExpId(baseExpId: JsonField) = apply { this.baseExpId = baseExpId } - - /** - * Identifier of the linked dataset, or null if the experiment is not linked to a - * dataset - */ - fun datasetId(datasetId: String?) = datasetId(JsonField.ofNullable(datasetId)) - - /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ - fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) - - /** - * Sets [Builder.datasetId] to an arbitrary JSON value. - * - * You should usually call [Builder.datasetId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun datasetId(datasetId: JsonField) = apply { this.datasetId = datasetId } - - /** - * Version number of the linked dataset the experiment was run against. This can be used - * to reproduce the experiment after the dataset has been modified. - */ - fun datasetVersion(datasetVersion: String?) = - datasetVersion(JsonField.ofNullable(datasetVersion)) - - /** Alias for calling [Builder.datasetVersion] with `datasetVersion.orElse(null)`. */ - fun datasetVersion(datasetVersion: Optional) = - datasetVersion(datasetVersion.getOrNull()) - - /** - * Sets [Builder.datasetVersion] to an arbitrary JSON value. - * - * You should usually call [Builder.datasetVersion] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun datasetVersion(datasetVersion: JsonField) = apply { - this.datasetVersion = datasetVersion - } - - /** Textual description of the experiment */ - fun description(description: String?) = description(JsonField.ofNullable(description)) - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } - - /** - * Normally, creating an experiment with the same name as an existing experiment will - * return the existing one un-modified. But if `ensure_new` is true, registration will - * generate a new experiment with a unique name in case of a conflict. - */ - fun ensureNew(ensureNew: Boolean?) = ensureNew(JsonField.ofNullable(ensureNew)) - - /** - * Alias for [Builder.ensureNew]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun ensureNew(ensureNew: Boolean) = ensureNew(ensureNew as Boolean?) - - /** Alias for calling [Builder.ensureNew] with `ensureNew.orElse(null)`. */ - fun ensureNew(ensureNew: Optional) = ensureNew(ensureNew.getOrNull()) - - /** - * Sets [Builder.ensureNew] to an arbitrary JSON value. - * - * You should usually call [Builder.ensureNew] with a well-typed [Boolean] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun ensureNew(ensureNew: JsonField) = apply { this.ensureNew = ensureNew } - - /** User-controlled metadata about the experiment */ - 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 additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Name of the experiment. Within a project, experiment names are unique */ - fun name(name: String?) = name(JsonField.ofNullable(name)) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Alias for calling [Builder.name] with `name.orElse(null)`. */ - fun name(name: Optional) = name(name.getOrNull()) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** - * 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 putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** - * Whether or not the experiment is public. Public experiments can be viewed by anybody - * inside or outside the organization - */ - fun public_(public_: Boolean?) = public_(JsonField.ofNullable(public_)) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** - * Alias for [Builder.public_]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun public_(public_: Boolean) = public_(public_ as Boolean?) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.public_] with `public_.orElse(null)`. */ - fun public_(public_: Optional) = public_(public_.getOrNull()) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * Sets [Builder.public_] to an arbitrary JSON value. - * - * You should usually call [Builder.public_] with a well-typed [Boolean] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun public_(public_: JsonField) = apply { this.public_ = public_ } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** Metadata about the state of the repo when the experiment was created */ - fun repoInfo(repoInfo: RepoInfo?) = repoInfo(JsonField.ofNullable(repoInfo)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.repoInfo] with `repoInfo.orElse(null)`. */ - fun repoInfo(repoInfo: Optional) = repoInfo(repoInfo.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.repoInfo] to an arbitrary JSON value. - * - * You should usually call [Builder.repoInfo] with a well-typed [RepoInfo] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun repoInfo(repoInfo: JsonField) = apply { this.repoInfo = repoInfo } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .projectId() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("projectId", projectId), - baseExpId, - datasetId, - datasetVersion, - description, - ensureNew, - metadata, - name, - public_, - repoInfo, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && projectId == other.projectId && baseExpId == other.baseExpId && datasetId == other.datasetId && datasetVersion == other.datasetVersion && description == other.description && ensureNew == other.ensureNew && metadata == other.metadata && name == other.name && public_ == other.public_ && repoInfo == other.repoInfo && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(projectId, baseExpId, datasetId, datasetVersion, description, ensureNew, metadata, name, public_, repoInfo, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{projectId=$projectId, baseExpId=$baseExpId, datasetId=$datasetId, datasetVersion=$datasetVersion, description=$description, ensureNew=$ensureNew, metadata=$metadata, name=$name, public_=$public_, repoInfo=$repoInfo, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [ExperimentCreateParams]. + * Returns an immutable instance of [ExperimentCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java * .projectId() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): ExperimentCreateParams = + ExperimentCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [ExperimentCreateParams]. */ - @NoAutoDetect - class Builder internal constructor() { + fun _body(): Body = body - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + override fun _headers(): Headers = additionalHeaders - @JvmSynthetic - internal fun from(experimentCreateParams: ExperimentCreateParams) = apply { - body = experimentCreateParams.body.toBuilder() - additionalHeaders = experimentCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = experimentCreateParams.additionalQueryParams.toBuilder() - } + override fun _queryParams(): QueryParams = additionalQueryParams - /** Unique identifier for the project that the experiment belongs under */ - fun projectId(projectId: String) = apply { body.projectId(projectId) } + class Body + private constructor( + private val projectId: JsonField, + private val baseExpId: JsonField, + private val datasetId: JsonField, + private val datasetVersion: JsonField, + private val description: JsonField, + private val ensureNew: JsonField, + private val metadata: JsonField, + private val name: JsonField, + private val public_: JsonField, + private val repoInfo: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("project_id") + @ExcludeMissing + projectId: JsonField = JsonMissing.of(), + @JsonProperty("base_exp_id") + @ExcludeMissing + baseExpId: JsonField = JsonMissing.of(), + @JsonProperty("dataset_id") + @ExcludeMissing + datasetId: JsonField = JsonMissing.of(), + @JsonProperty("dataset_version") + @ExcludeMissing + datasetVersion: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("ensure_new") + @ExcludeMissing + ensureNew: JsonField = JsonMissing.of(), + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("public") @ExcludeMissing public_: JsonField = JsonMissing.of(), + @JsonProperty("repo_info") + @ExcludeMissing + repoInfo: JsonField = JsonMissing.of(), + ) : this( + projectId, + baseExpId, + datasetId, + datasetVersion, + description, + ensureNew, + metadata, + name, + public_, + repoInfo, + mutableMapOf(), + ) /** - * Sets [Builder.projectId] to an arbitrary JSON value. + * Unique identifier for the project that the experiment belongs under * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException 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 projectId(projectId: JsonField) = apply { body.projectId(projectId) } - - /** Id of default base experiment to compare against when viewing this experiment */ - fun baseExpId(baseExpId: String?) = apply { body.baseExpId(baseExpId) } - - /** Alias for calling [Builder.baseExpId] with `baseExpId.orElse(null)`. */ - fun baseExpId(baseExpId: Optional) = baseExpId(baseExpId.getOrNull()) + fun projectId(): String = projectId.getRequired("project_id") /** - * Sets [Builder.baseExpId] to an arbitrary JSON value. + * Id of default base experiment to compare against when viewing this experiment * - * You should usually call [Builder.baseExpId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun baseExpId(baseExpId: JsonField) = apply { body.baseExpId(baseExpId) } + fun baseExpId(): Optional = baseExpId.getOptional("base_exp_id") /** * Identifier of the linked dataset, or null if the experiment is not linked to a dataset + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun datasetId(datasetId: String?) = apply { body.datasetId(datasetId) } + fun datasetId(): Optional = datasetId.getOptional("dataset_id") - /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ - fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) + /** + * Version number of the linked dataset the experiment was run against. This can be used to + * reproduce the experiment after the dataset has been modified. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun datasetVersion(): Optional = datasetVersion.getOptional("dataset_version") /** - * Sets [Builder.datasetId] to an arbitrary JSON value. + * Textual description of the experiment * - * You should usually call [Builder.datasetId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun datasetId(datasetId: JsonField) = apply { body.datasetId(datasetId) } + fun description(): Optional = description.getOptional("description") /** - * Version number of the linked dataset the experiment was run against. This can be used to - * reproduce the experiment after the dataset has been modified. + * Normally, creating an experiment with the same name as an existing experiment will return + * the existing one un-modified. But if `ensure_new` is true, registration will generate a + * new experiment with a unique name in case of a conflict. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun datasetVersion(datasetVersion: String?) = apply { body.datasetVersion(datasetVersion) } + fun ensureNew(): Optional = ensureNew.getOptional("ensure_new") - /** Alias for calling [Builder.datasetVersion] with `datasetVersion.orElse(null)`. */ - fun datasetVersion(datasetVersion: Optional) = - datasetVersion(datasetVersion.getOrNull()) + /** + * User-controlled metadata about the experiment + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") /** - * Sets [Builder.datasetVersion] to an arbitrary JSON value. + * Name of the experiment. Within a project, experiment names are unique * - * You should usually call [Builder.datasetVersion] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun datasetVersion(datasetVersion: JsonField) = apply { - body.datasetVersion(datasetVersion) - } + fun name(): Optional = name.getOptional("name") - /** Textual description of the experiment */ - fun description(description: String?) = apply { body.description(description) } + /** + * Whether or not the experiment is public. Public experiments can be viewed by anybody + * inside or outside the organization + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun public_(): Optional = public_.getOptional("public") - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + /** + * Metadata about the state of the repo when the experiment was created + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun repoInfo(): Optional = repoInfo.getOptional("repo_info") + + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId /** - * Sets [Builder.description] to an arbitrary JSON value. + * Returns the raw JSON value of [baseExpId]. * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [baseExpId], this method doesn't throw if the JSON field has an unexpected type. */ - fun description(description: JsonField) = apply { body.description(description) } + @JsonProperty("base_exp_id") @ExcludeMissing fun _baseExpId(): JsonField = baseExpId /** - * Normally, creating an experiment with the same name as an existing experiment will return - * the existing one un-modified. But if `ensure_new` is true, registration will generate a - * new experiment with a unique name in case of a conflict. + * Returns the raw JSON value of [datasetId]. + * + * Unlike [datasetId], this method doesn't throw if the JSON field has an unexpected type. */ - fun ensureNew(ensureNew: Boolean?) = apply { body.ensureNew(ensureNew) } + @JsonProperty("dataset_id") @ExcludeMissing fun _datasetId(): JsonField = datasetId /** - * Alias for [Builder.ensureNew]. + * Returns the raw JSON value of [datasetVersion]. * - * This unboxed primitive overload exists for backwards compatibility. + * Unlike [datasetVersion], this method doesn't throw if the JSON field has an unexpected + * type. */ - fun ensureNew(ensureNew: Boolean) = ensureNew(ensureNew as Boolean?) - - /** Alias for calling [Builder.ensureNew] with `ensureNew.orElse(null)`. */ - fun ensureNew(ensureNew: Optional) = ensureNew(ensureNew.getOrNull()) + @JsonProperty("dataset_version") + @ExcludeMissing + fun _datasetVersion(): JsonField = datasetVersion /** - * Sets [Builder.ensureNew] to an arbitrary JSON value. + * Returns the raw JSON value of [description]. * - * You should usually call [Builder.ensureNew] with a well-typed [Boolean] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. */ - fun ensureNew(ensureNew: JsonField) = apply { body.ensureNew(ensureNew) } - - /** User-controlled metadata about the experiment */ - fun metadata(metadata: Metadata?) = apply { body.metadata(metadata) } - - /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ - fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description /** - * Sets [Builder.metadata] to an arbitrary JSON value. + * Returns the raw JSON value of [ensureNew]. * - * 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. + * Unlike [ensureNew], this method doesn't throw if the JSON field has an unexpected type. */ - fun metadata(metadata: JsonField) = apply { body.metadata(metadata) } - - /** Name of the experiment. Within a project, experiment names are unique */ - fun name(name: String?) = apply { body.name(name) } - - /** Alias for calling [Builder.name] with `name.orElse(null)`. */ - fun name(name: Optional) = name(name.getOrNull()) + @JsonProperty("ensure_new") @ExcludeMissing fun _ensureNew(): JsonField = ensureNew /** - * Sets [Builder.name] to an arbitrary JSON value. + * Returns the raw JSON value of [metadata]. * - * 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. + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. */ - fun name(name: JsonField) = apply { body.name(name) } + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata /** - * Whether or not the experiment is public. Public experiments can be viewed by anybody - * inside or outside the organization + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. */ - fun public_(public_: Boolean?) = apply { body.public_(public_) } + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name /** - * Alias for [Builder.public_]. + * Returns the raw JSON value of [public_]. * - * This unboxed primitive overload exists for backwards compatibility. + * Unlike [public_], this method doesn't throw if the JSON field has an unexpected type. */ - fun public_(public_: Boolean) = public_(public_ as Boolean?) - - /** Alias for calling [Builder.public_] with `public_.orElse(null)`. */ - fun public_(public_: Optional) = public_(public_.getOrNull()) + @JsonProperty("public") @ExcludeMissing fun _public_(): JsonField = public_ /** - * Sets [Builder.public_] to an arbitrary JSON value. + * Returns the raw JSON value of [repoInfo]. * - * You should usually call [Builder.public_] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [repoInfo], this method doesn't throw if the JSON field has an unexpected type. */ - fun public_(public_: JsonField) = apply { body.public_(public_) } + @JsonProperty("repo_info") @ExcludeMissing fun _repoInfo(): JsonField = repoInfo - /** Metadata about the state of the repo when the experiment was created */ - fun repoInfo(repoInfo: RepoInfo?) = apply { body.repoInfo(repoInfo) } + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } - /** Alias for calling [Builder.repoInfo] with `repoInfo.orElse(null)`. */ - fun repoInfo(repoInfo: Optional) = repoInfo(repoInfo.getOrNull()) + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - /** - * Sets [Builder.repoInfo] to an arbitrary JSON value. - * - * You should usually call [Builder.repoInfo] with a well-typed [RepoInfo] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun repoInfo(repoInfo: JsonField) = apply { body.repoInfo(repoInfo) } + fun toBuilder() = Builder().from(this) - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) - } + companion object { - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .projectId() + * ``` + */ + @JvmStatic fun builder() = Builder() } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) - } + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var projectId: JsonField? = null + private var baseExpId: JsonField = JsonMissing.of() + private var datasetId: JsonField = JsonMissing.of() + private var datasetVersion: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var ensureNew: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var public_: JsonField = JsonMissing.of() + private var repoInfo: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + projectId = body.projectId + baseExpId = body.baseExpId + datasetId = body.datasetId + datasetVersion = body.datasetVersion + description = body.description + ensureNew = body.ensureNew + metadata = body.metadata + name = body.name + public_ = body.public_ + repoInfo = body.repoInfo + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Unique identifier for the project that the experiment belongs under */ + fun projectId(projectId: String) = projectId(JsonField.of(projectId)) + + /** + * Sets [Builder.projectId] to an arbitrary JSON value. + * + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun projectId(projectId: JsonField) = apply { this.projectId = projectId } + + /** Id of default base experiment to compare against when viewing this experiment */ + fun baseExpId(baseExpId: String?) = baseExpId(JsonField.ofNullable(baseExpId)) + + /** Alias for calling [Builder.baseExpId] with `baseExpId.orElse(null)`. */ + fun baseExpId(baseExpId: Optional) = baseExpId(baseExpId.getOrNull()) + + /** + * Sets [Builder.baseExpId] to an arbitrary JSON value. + * + * You should usually call [Builder.baseExpId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun baseExpId(baseExpId: JsonField) = apply { this.baseExpId = baseExpId } + + /** + * Identifier of the linked dataset, or null if the experiment is not linked to a + * dataset + */ + fun datasetId(datasetId: String?) = datasetId(JsonField.ofNullable(datasetId)) + + /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ + fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) + + /** + * Sets [Builder.datasetId] to an arbitrary JSON value. + * + * You should usually call [Builder.datasetId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun datasetId(datasetId: JsonField) = apply { this.datasetId = datasetId } + + /** + * Version number of the linked dataset the experiment was run against. This can be used + * to reproduce the experiment after the dataset has been modified. + */ + fun datasetVersion(datasetVersion: String?) = + datasetVersion(JsonField.ofNullable(datasetVersion)) + + /** Alias for calling [Builder.datasetVersion] with `datasetVersion.orElse(null)`. */ + fun datasetVersion(datasetVersion: Optional) = + datasetVersion(datasetVersion.getOrNull()) + + /** + * Sets [Builder.datasetVersion] to an arbitrary JSON value. + * + * You should usually call [Builder.datasetVersion] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun datasetVersion(datasetVersion: JsonField) = apply { + this.datasetVersion = datasetVersion + } + + /** Textual description of the experiment */ + fun description(description: String?) = description(JsonField.ofNullable(description)) + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + + /** + * Normally, creating an experiment with the same name as an existing experiment will + * return the existing one un-modified. But if `ensure_new` is true, registration will + * generate a new experiment with a unique name in case of a conflict. + */ + fun ensureNew(ensureNew: Boolean?) = ensureNew(JsonField.ofNullable(ensureNew)) + + /** + * Alias for [Builder.ensureNew]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun ensureNew(ensureNew: Boolean) = ensureNew(ensureNew as Boolean?) + + /** Alias for calling [Builder.ensureNew] with `ensureNew.orElse(null)`. */ + fun ensureNew(ensureNew: Optional) = ensureNew(ensureNew.getOrNull()) + + /** + * Sets [Builder.ensureNew] to an arbitrary JSON value. + * + * You should usually call [Builder.ensureNew] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun ensureNew(ensureNew: JsonField) = apply { this.ensureNew = ensureNew } + + /** User-controlled metadata about the experiment */ + fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** + * 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 additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** Name of the experiment. Within a project, experiment names are unique */ + fun name(name: String?) = name(JsonField.ofNullable(name)) - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** + * 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 putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * Whether or not the experiment is public. Public experiments can be viewed by anybody + * inside or outside the organization + */ + fun public_(public_: Boolean?) = public_(JsonField.ofNullable(public_)) - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Alias for [Builder.public_]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun public_(public_: Boolean) = public_(public_ as Boolean?) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.public_] with `public_.orElse(null)`. */ + fun public_(public_: Optional) = public_(public_.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.public_] to an arbitrary JSON value. + * + * You should usually call [Builder.public_] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun public_(public_: JsonField) = apply { this.public_ = public_ } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** Metadata about the state of the repo when the experiment was created */ + fun repoInfo(repoInfo: RepoInfo?) = repoInfo(JsonField.ofNullable(repoInfo)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.repoInfo] with `repoInfo.orElse(null)`. */ + fun repoInfo(repoInfo: Optional) = repoInfo(repoInfo.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.repoInfo] to an arbitrary JSON value. + * + * You should usually call [Builder.repoInfo] with a well-typed [RepoInfo] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun repoInfo(repoInfo: JsonField) = apply { this.repoInfo = repoInfo } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .projectId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("projectId", projectId), + baseExpId, + datasetId, + datasetVersion, + description, + ensureNew, + metadata, + name, + public_, + repoInfo, + additionalProperties.toMutableMap(), + ) } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + private var validated: Boolean = false - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun validate(): Body = apply { + if (validated) { + return@apply } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) + projectId() + baseExpId() + datasetId() + datasetVersion() + description() + ensureNew() + metadata().ifPresent { it.validate() } + name() + public_() + repoInfo().ifPresent { it.validate() } + validated = true } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + /** + * Returns 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 (projectId.asKnown().isPresent) 1 else 0) + + (if (baseExpId.asKnown().isPresent) 1 else 0) + + (if (datasetId.asKnown().isPresent) 1 else 0) + + (if (datasetVersion.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (ensureNew.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (public_.asKnown().isPresent) 1 else 0) + + (repoInfo.asKnown().getOrNull()?.validity() ?: 0) - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + return /* spotless:off */ other is Body && projectId == other.projectId && baseExpId == other.baseExpId && datasetId == other.datasetId && datasetVersion == other.datasetVersion && description == other.description && ensureNew == other.ensureNew && metadata == other.metadata && name == other.name && public_ == other.public_ && repoInfo == other.repoInfo && additionalProperties == other.additionalProperties /* spotless:on */ } - /** - * Returns an immutable instance of [ExperimentCreateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .projectId() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): ExperimentCreateParams = - ExperimentCreateParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(projectId, baseExpId, datasetId, datasetVersion, description, ensureNew, metadata, name, public_, repoInfo, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{projectId=$projectId, baseExpId=$baseExpId, datasetId=$datasetId, datasetVersion=$datasetVersion, description=$description, ensureNew=$ensureNew, metadata=$metadata, name=$name, public_=$public_, repoInfo=$repoInfo, additionalProperties=$additionalProperties}" } /** User-controlled metadata about the experiment */ - @NoAutoDetect class Metadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -1123,6 +1172,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentDeleteParams.kt index 78bec198..82be2d53 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentDeleteParams.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,26 +23,11 @@ private constructor( /** Experiment id */ fun experimentId(): String = experimentId - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> experimentId - else -> "" - } - } + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -61,7 +45,6 @@ private constructor( } /** A builder for [ExperimentDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var experimentId: String? = null @@ -222,6 +205,19 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> experimentId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentEvent.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentEvent.kt index aa0f500c..8190a183 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentEvent.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentEvent.kt @@ -6,10 +6,8 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -17,67 +15,94 @@ import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class ExperimentEvent -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("_xact_id") - @ExcludeMissing - private val _xactId: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("experiment_id") - @ExcludeMissing - private val experimentId: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("root_span_id") - @ExcludeMissing - private val rootSpanId: JsonField = JsonMissing.of(), - @JsonProperty("span_id") - @ExcludeMissing - private val spanId: JsonField = JsonMissing.of(), - @JsonProperty("context") - @ExcludeMissing - private val context: JsonField = JsonMissing.of(), - @JsonProperty("error") @ExcludeMissing private val error: JsonValue = JsonMissing.of(), - @JsonProperty("expected") @ExcludeMissing private val expected: JsonValue = JsonMissing.of(), - @JsonProperty("input") @ExcludeMissing private val input: JsonValue = JsonMissing.of(), - @JsonProperty("is_root") - @ExcludeMissing - private val isRoot: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("metrics") - @ExcludeMissing - private val metrics: JsonField = JsonMissing.of(), - @JsonProperty("origin") - @ExcludeMissing - private val origin: JsonField = JsonMissing.of(), - @JsonProperty("output") @ExcludeMissing private val output: JsonValue = JsonMissing.of(), - @JsonProperty("scores") - @ExcludeMissing - private val scores: JsonField = JsonMissing.of(), - @JsonProperty("span_attributes") - @ExcludeMissing - private val spanAttributes: JsonField = JsonMissing.of(), - @JsonProperty("span_parents") - @ExcludeMissing - private val spanParents: JsonField> = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val _xactId: JsonField, + private val created: JsonField, + private val experimentId: JsonField, + private val projectId: JsonField, + private val rootSpanId: JsonField, + private val spanId: JsonField, + private val context: JsonField, + private val error: JsonValue, + private val expected: JsonValue, + private val input: JsonValue, + private val isRoot: JsonField, + private val metadata: JsonField, + private val metrics: JsonField, + private val origin: JsonField, + private val output: JsonValue, + private val scores: JsonField, + private val spanAttributes: JsonField, + private val spanParents: JsonField>, + private val tags: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("_xact_id") @ExcludeMissing _xactId: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("experiment_id") + @ExcludeMissing + experimentId: JsonField = JsonMissing.of(), + @JsonProperty("project_id") @ExcludeMissing projectId: JsonField = JsonMissing.of(), + @JsonProperty("root_span_id") + @ExcludeMissing + rootSpanId: JsonField = JsonMissing.of(), + @JsonProperty("span_id") @ExcludeMissing spanId: JsonField = JsonMissing.of(), + @JsonProperty("context") @ExcludeMissing context: JsonField = JsonMissing.of(), + @JsonProperty("error") @ExcludeMissing error: JsonValue = JsonMissing.of(), + @JsonProperty("expected") @ExcludeMissing expected: JsonValue = JsonMissing.of(), + @JsonProperty("input") @ExcludeMissing input: JsonValue = JsonMissing.of(), + @JsonProperty("is_root") @ExcludeMissing isRoot: JsonField = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("metrics") @ExcludeMissing metrics: JsonField = JsonMissing.of(), + @JsonProperty("origin") + @ExcludeMissing + origin: JsonField = JsonMissing.of(), + @JsonProperty("output") @ExcludeMissing output: JsonValue = JsonMissing.of(), + @JsonProperty("scores") @ExcludeMissing scores: JsonField = JsonMissing.of(), + @JsonProperty("span_attributes") + @ExcludeMissing + spanAttributes: JsonField = JsonMissing.of(), + @JsonProperty("span_parents") + @ExcludeMissing + spanParents: JsonField> = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this( + id, + _xactId, + created, + experimentId, + projectId, + rootSpanId, + spanId, + context, + error, + expected, + input, + isRoot, + metadata, + metrics, + origin, + output, + scores, + spanAttributes, + spanParents, + tags, + mutableMapOf(), + ) + /** * A unique identifier for the experiment event. If you don't provide one, BrainTrust will * generate one for you @@ -147,7 +172,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun context(): Optional = Optional.ofNullable(context.getNullable("context")) + fun context(): Optional = context.getOptional("context") /** The error that occurred, if any. */ @JsonProperty("error") @ExcludeMissing fun _error(): JsonValue = error @@ -176,7 +201,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun isRoot(): Optional = Optional.ofNullable(isRoot.getNullable("is_root")) + fun isRoot(): Optional = isRoot.getOptional("is_root") /** * A dictionary with additional data about the test example, model outputs, or just about @@ -188,7 +213,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** * Metrics are numerical measurements tracking the execution of the code that produced the @@ -198,7 +223,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metrics(): Optional = Optional.ofNullable(metrics.getNullable("metrics")) + fun metrics(): Optional = metrics.getOptional("metrics") /** * Indicates the event was copied from another object. @@ -206,7 +231,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun origin(): Optional = Optional.ofNullable(origin.getNullable("origin")) + fun origin(): Optional = origin.getOptional("origin") /** * The output of your application, including post-processing (an arbitrary, JSON serializable @@ -229,7 +254,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun scores(): Optional = Optional.ofNullable(scores.getNullable("scores")) + fun scores(): Optional = scores.getOptional("scores") /** * Human-identifying attributes of the span, such as name, type, etc. @@ -237,8 +262,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spanAttributes(): Optional = - Optional.ofNullable(spanAttributes.getNullable("span_attributes")) + fun spanAttributes(): Optional = spanAttributes.getOptional("span_attributes") /** * An array of the parent `span_ids` of this experiment event. This should be empty for the root @@ -247,8 +271,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spanParents(): Optional> = - Optional.ofNullable(spanParents.getNullable("span_parents")) + fun spanParents(): Optional> = spanParents.getOptional("span_parents") /** * A list of tags to log @@ -256,7 +279,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [id]. @@ -376,35 +399,15 @@ private constructor( */ @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ExperimentEvent = apply { - if (validated) { - return@apply - } - - id() - _xactId() - created() - experimentId() - projectId() - rootSpanId() - spanId() - context().ifPresent { it.validate() } - isRoot() - metadata().ifPresent { it.validate() } - metrics().ifPresent { it.validate() } - origin().ifPresent { it.validate() } - scores().ifPresent { it.validate() } - spanAttributes().ifPresent { it.validate() } - spanParents() - tags() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -852,40 +855,101 @@ private constructor( spanAttributes, (spanParents ?: JsonMissing.of()).map { it.toImmutable() }, (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): ExperimentEvent = apply { + if (validated) { + return@apply + } + + id() + _xactId() + created() + experimentId() + projectId() + rootSpanId() + spanId() + context().ifPresent { it.validate() } + isRoot() + metadata().ifPresent { it.validate() } + metrics().ifPresent { it.validate() } + origin().ifPresent { it.validate() } + scores().ifPresent { it.validate() } + spanAttributes().ifPresent { it.validate() } + spanParents() + tags() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (_xactId.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (experimentId.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (rootSpanId.asKnown().isPresent) 1 else 0) + + (if (spanId.asKnown().isPresent) 1 else 0) + + (context.asKnown().getOrNull()?.validity() ?: 0) + + (if (isRoot.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (metrics.asKnown().getOrNull()?.validity() ?: 0) + + (origin.asKnown().getOrNull()?.validity() ?: 0) + + (scores.asKnown().getOrNull()?.validity() ?: 0) + + (spanAttributes.asKnown().getOrNull()?.validity() ?: 0) + + (spanParents.asKnown().getOrNull()?.size ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + /** * Context is additional information about the code that produced the experiment event. It is * essentially the textual counterpart to `metrics`. Use the `caller_*` attributes to track the * location in code which produced the experiment event */ - @NoAutoDetect class Context - @JsonCreator private constructor( - @JsonProperty("caller_filename") - @ExcludeMissing - private val callerFilename: JsonField = JsonMissing.of(), - @JsonProperty("caller_functionname") - @ExcludeMissing - private val callerFunctionname: JsonField = JsonMissing.of(), - @JsonProperty("caller_lineno") - @ExcludeMissing - private val callerLineno: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val callerFilename: JsonField, + private val callerFunctionname: JsonField, + private val callerLineno: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("caller_filename") + @ExcludeMissing + callerFilename: JsonField = JsonMissing.of(), + @JsonProperty("caller_functionname") + @ExcludeMissing + callerFunctionname: JsonField = JsonMissing.of(), + @JsonProperty("caller_lineno") + @ExcludeMissing + callerLineno: JsonField = JsonMissing.of(), + ) : this(callerFilename, callerFunctionname, callerLineno, mutableMapOf()) + /** * Name of the file in code where the experiment event was created * * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun callerFilename(): Optional = - Optional.ofNullable(callerFilename.getNullable("caller_filename")) + fun callerFilename(): Optional = callerFilename.getOptional("caller_filename") /** * The function in code which created the experiment event @@ -894,7 +958,7 @@ private constructor( * the server responded with an unexpected value). */ fun callerFunctionname(): Optional = - Optional.ofNullable(callerFunctionname.getNullable("caller_functionname")) + callerFunctionname.getOptional("caller_functionname") /** * Line of code where the experiment event was created @@ -902,8 +966,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun callerLineno(): Optional = - Optional.ofNullable(callerLineno.getNullable("caller_lineno")) + fun callerLineno(): Optional = callerLineno.getOptional("caller_lineno") /** * Returns the raw JSON value of [callerFilename]. @@ -935,22 +998,15 @@ private constructor( @ExcludeMissing fun _callerLineno(): JsonField = callerLineno + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Context = apply { - if (validated) { - return@apply - } - - callerFilename() - callerFunctionname() - callerLineno() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1070,10 +1126,43 @@ private constructor( callerFilename, callerFunctionname, callerLineno, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Context = apply { + if (validated) { + return@apply + } + + callerFilename() + callerFunctionname() + callerLineno() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (callerFilename.asKnown().isPresent) 1 else 0) + + (if (callerFunctionname.asKnown().isPresent) 1 else 0) + + (if (callerLineno.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1099,24 +1188,24 @@ private constructor( * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys * must be strings */ - @NoAutoDetect class Metadata - @JsonCreator private constructor( - @JsonProperty("model") - @ExcludeMissing - private val model: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val model: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of() + ) : this(model, mutableMapOf()) + /** * The model used for this example * * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [model]. @@ -1125,20 +1214,15 @@ private constructor( */ @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - model() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1199,9 +1283,36 @@ private constructor( * * Further updates to this [Builder] will not mutate the returned instance. */ - fun build(): Metadata = Metadata(model, additionalProperties.toImmutable()) + fun build(): Metadata = Metadata(model, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + model() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1225,36 +1336,51 @@ private constructor( * experiment event. Use "start" and "end" to track the time span over which the experiment * event was produced */ - @NoAutoDetect class Metrics - @JsonCreator private constructor( - @JsonProperty("caller_filename") - @ExcludeMissing - private val callerFilename: JsonValue = JsonMissing.of(), - @JsonProperty("caller_functionname") - @ExcludeMissing - private val callerFunctionname: JsonValue = JsonMissing.of(), - @JsonProperty("caller_lineno") - @ExcludeMissing - private val callerLineno: JsonValue = JsonMissing.of(), - @JsonProperty("completion_tokens") - @ExcludeMissing - private val completionTokens: JsonField = JsonMissing.of(), - @JsonProperty("end") @ExcludeMissing private val end: JsonField = JsonMissing.of(), - @JsonProperty("prompt_tokens") - @ExcludeMissing - private val promptTokens: JsonField = JsonMissing.of(), - @JsonProperty("start") - @ExcludeMissing - private val start: JsonField = JsonMissing.of(), - @JsonProperty("tokens") - @ExcludeMissing - private val tokens: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val callerFilename: JsonValue, + private val callerFunctionname: JsonValue, + private val callerLineno: JsonValue, + private val completionTokens: JsonField, + private val end: JsonField, + private val promptTokens: JsonField, + private val start: JsonField, + private val tokens: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("caller_filename") + @ExcludeMissing + callerFilename: JsonValue = JsonMissing.of(), + @JsonProperty("caller_functionname") + @ExcludeMissing + callerFunctionname: JsonValue = JsonMissing.of(), + @JsonProperty("caller_lineno") + @ExcludeMissing + callerLineno: JsonValue = JsonMissing.of(), + @JsonProperty("completion_tokens") + @ExcludeMissing + completionTokens: JsonField = JsonMissing.of(), + @JsonProperty("end") @ExcludeMissing end: JsonField = JsonMissing.of(), + @JsonProperty("prompt_tokens") + @ExcludeMissing + promptTokens: JsonField = JsonMissing.of(), + @JsonProperty("start") @ExcludeMissing start: JsonField = JsonMissing.of(), + @JsonProperty("tokens") @ExcludeMissing tokens: JsonField = JsonMissing.of(), + ) : this( + callerFilename, + callerFunctionname, + callerLineno, + completionTokens, + end, + promptTokens, + start, + tokens, + mutableMapOf(), + ) + /** This metric is deprecated */ @JsonProperty("caller_filename") @ExcludeMissing @@ -1275,8 +1401,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * A unix timestamp recording when the section of code which produced the experiment event @@ -1285,7 +1410,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun end(): Optional = Optional.ofNullable(end.getNullable("end")) + fun end(): Optional = end.getOptional("end") /** * The number of tokens in the prompt used to generate the experiment event (only set if @@ -1294,8 +1419,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * A unix timestamp recording when the section of code which produced the experiment event @@ -1304,7 +1428,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun start(): Optional = Optional.ofNullable(start.getNullable("start")) + fun start(): Optional = start.getOptional("start") /** * The total number of tokens in the input and output of the experiment event. @@ -1312,7 +1436,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun tokens(): Optional = Optional.ofNullable(tokens.getNullable("tokens")) + fun tokens(): Optional = tokens.getOptional("tokens") /** * Returns the raw JSON value of [completionTokens]. @@ -1355,24 +1479,15 @@ private constructor( */ @JsonProperty("tokens") @ExcludeMissing fun _tokens(): JsonField = tokens + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metrics = apply { - if (validated) { - return@apply - } - - completionTokens() - end() - promptTokens() - start() - tokens() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1586,10 +1701,47 @@ private constructor( promptTokens, start, tokens, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Metrics = apply { + if (validated) { + return@apply + } + + completionTokens() + end() + promptTokens() + start() + tokens() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (completionTokens.asKnown().isPresent) 1 else 0) + + (if (end.asKnown().isPresent) 1 else 0) + + (if (promptTokens.asKnown().isPresent) 1 else 0) + + (if (start.asKnown().isPresent) 1 else 0) + + (if (tokens.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1617,28 +1769,17 @@ private constructor( * whether the summarization was covering similar concepts or not. You can use these scores to * help you sort, filter, and compare experiments */ - @NoAutoDetect class Scores @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Scores = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -1684,6 +1825,34 @@ private constructor( fun build(): Scores = Scores(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Scores = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFeedbackParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFeedbackParams.kt index 2558dfff..5c621452 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFeedbackParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFeedbackParams.kt @@ -6,20 +6,20 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 kotlin.jvm.optionals.getOrNull /** Log feedback for a set of experiment events */ class ExperimentFeedbackParams @@ -54,171 +54,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> experimentId - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("feedback") - @ExcludeMissing - private val feedback: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * A list of experiment feedback items - * - * @throws BraintrustInvalidDataException 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 feedback(): List = feedback.getRequired("feedback") - - /** - * Returns the raw JSON value of [feedback]. - * - * Unlike [feedback], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("feedback") - @ExcludeMissing - fun _feedback(): JsonField> = feedback - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - feedback().forEach { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .feedback() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var feedback: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - feedback = body.feedback.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** A list of experiment feedback items */ - fun feedback(feedback: List) = feedback(JsonField.of(feedback)) - - /** - * Sets [Builder.feedback] to an arbitrary JSON value. - * - * You should usually call [Builder.feedback] with a well-typed - * `List` value instead. This method is primarily for setting - * the field to an undocumented or not yet supported value. - */ - fun feedback(feedback: JsonField>) = apply { - this.feedback = feedback.map { it.toMutableList() } - } - - /** - * Adds a single [FeedbackExperimentItem] to [Builder.feedback]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addFeedback(feedback: FeedbackExperimentItem) = apply { - this.feedback = - (this.feedback ?: JsonField.of(mutableListOf())).also { - checkKnown("feedback", it).add(feedback) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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 - * .feedback() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("feedback", feedback).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && feedback == other.feedback && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(feedback, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{feedback=$feedback, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -236,7 +71,6 @@ private constructor( } /** A builder for [ExperimentFeedbackParams]. */ - @NoAutoDetect class Builder internal constructor() { private var experimentId: String? = null @@ -255,6 +89,15 @@ private constructor( /** Experiment id */ fun experimentId(experimentId: String) = apply { this.experimentId = experimentId } + /** + * 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: + * - [feedback] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** A list of experiment feedback items */ fun feedback(feedback: List) = apply { body.feedback(feedback) } @@ -415,6 +258,196 @@ private constructor( ) } + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> experimentId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val feedback: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("feedback") + @ExcludeMissing + feedback: JsonField> = JsonMissing.of() + ) : this(feedback, mutableMapOf()) + + /** + * A list of experiment feedback items + * + * @throws BraintrustInvalidDataException 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 feedback(): List = feedback.getRequired("feedback") + + /** + * Returns the raw JSON value of [feedback]. + * + * Unlike [feedback], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("feedback") + @ExcludeMissing + fun _feedback(): JsonField> = feedback + + @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 + * .feedback() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var feedback: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + feedback = body.feedback.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** A list of experiment feedback items */ + fun feedback(feedback: List) = feedback(JsonField.of(feedback)) + + /** + * Sets [Builder.feedback] to an arbitrary JSON value. + * + * You should usually call [Builder.feedback] with a well-typed + * `List` value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun feedback(feedback: JsonField>) = apply { + this.feedback = feedback.map { it.toMutableList() } + } + + /** + * Adds a single [FeedbackExperimentItem] to [Builder.feedback]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFeedback(feedback: FeedbackExperimentItem) = apply { + this.feedback = + (this.feedback ?: JsonField.of(mutableListOf())).also { + checkKnown("feedback", it).add(feedback) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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 + * .feedback() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("feedback", feedback).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + feedback().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (feedback.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && feedback == other.feedback && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(feedback, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{feedback=$feedback, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFetchParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFetchParams.kt index 93faaa22..c96284e4 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFetchParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFetchParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -86,26 +85,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - limit?.let { put("limit", it.toString()) } - maxRootSpanId?.let { put("max_root_span_id", it) } - maxXactId?.let { put("max_xact_id", it) } - version?.let { put("version", it) } - putAll(additionalQueryParams) - } - .build() - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> experimentId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -122,7 +101,6 @@ private constructor( } /** A builder for [ExperimentFetchParams]. */ - @NoAutoDetect class Builder internal constructor() { private var experimentId: String? = null @@ -342,6 +320,25 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> experimentId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + limit?.let { put("limit", it.toString()) } + maxRootSpanId?.let { put("max_root_span_id", it) } + maxXactId?.let { put("max_xact_id", it) } + version?.let { put("version", it) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFetchPostParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFetchPostParams.kt index 180f8e6a..d1c52fb9 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFetchPostParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFetchPostParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -154,41 +152,53 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) - override fun _headers(): Headers = additionalHeaders + companion object { - override fun _queryParams(): QueryParams = additionalQueryParams + /** + * Returns a mutable builder for constructing an instance of [ExperimentFetchPostParams]. + * + * The following fields are required: + * ```java + * .experimentId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - fun getPathParam(index: Int): String { - return when (index) { - 0 -> experimentId - else -> "" + /** A builder for [ExperimentFetchPostParams]. */ + class Builder internal constructor() { + + private var experimentId: 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(experimentFetchPostParams: ExperimentFetchPostParams) = apply { + experimentId = experimentFetchPostParams.experimentId + body = experimentFetchPostParams.body.toBuilder() + additionalHeaders = experimentFetchPostParams.additionalHeaders.toBuilder() + additionalQueryParams = experimentFetchPostParams.additionalQueryParams.toBuilder() } - } - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("cursor") - @ExcludeMissing - private val cursor: JsonField = JsonMissing.of(), - @JsonProperty("limit") - @ExcludeMissing - private val limit: JsonField = JsonMissing.of(), - @JsonProperty("max_root_span_id") - @ExcludeMissing - private val maxRootSpanId: JsonField = JsonMissing.of(), - @JsonProperty("max_xact_id") - @ExcludeMissing - private val maxXactId: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** Experiment id */ + fun experimentId(experimentId: String) = apply { this.experimentId = experimentId } + + /** + * 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: + * - [cursor] + * - [limit] + * - [maxRootSpanId] + * - [maxXactId] + * - [version] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } /** * An opaque string to be used as a cursor for the next page of results, in order from @@ -196,11 +206,19 @@ private constructor( * * The string can be obtained directly from the `cursor` property of the previous fetch * query + */ + fun cursor(cursor: String?) = apply { body.cursor(cursor) } + + /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ + fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) + + /** + * Sets [Builder.cursor] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.cursor] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - fun cursor(): Optional = Optional.ofNullable(cursor.getNullable("cursor")) + fun cursor(cursor: JsonField) = apply { body.cursor(cursor) } /** * limit the number of traces fetched @@ -216,11 +234,26 @@ private constructor( * The `limit` parameter controls the number of full traces to return. So you may end up * with more individual rows than the specified limit if you are fetching events containing * traces. + */ + fun limit(limit: Long?) = apply { body.limit(limit) } + + /** + * Alias for [Builder.limit]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * This unboxed primitive overload exists for backwards compatibility. + */ + fun limit(limit: Long) = limit(limit as Long?) + + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) + + /** + * Sets [Builder.limit] to an arbitrary JSON value. + * + * You should usually call [Builder.limit] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - fun limit(): Optional = Optional.ofNullable(limit.getNullable("limit")) + fun limit(limit: JsonField) = apply { body.limit(limit) } /** * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor of @@ -233,12 +266,23 @@ private constructor( * cursor for the next page can be found as the row with the minimum (earliest) value of the * tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an overview of * paginating fetch queries. + */ + fun maxRootSpanId(maxRootSpanId: String?) = apply { body.maxRootSpanId(maxRootSpanId) } + + /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ + fun maxRootSpanId(maxRootSpanId: Optional) = + maxRootSpanId(maxRootSpanId.getOrNull()) + + /** + * Sets [Builder.maxRootSpanId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.maxRootSpanId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun maxRootSpanId(): Optional = - Optional.ofNullable(maxRootSpanId.getNullable("max_root_span_id")) + fun maxRootSpanId(maxRootSpanId: JsonField) = apply { + body.maxRootSpanId(maxRootSpanId) + } /** * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor of @@ -251,330 +295,212 @@ private constructor( * cursor for the next page can be found as the row with the minimum (earliest) value of the * tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an overview of * paginating fetch queries. + */ + fun maxXactId(maxXactId: String?) = apply { body.maxXactId(maxXactId) } + + /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ + fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) + + /** + * Sets [Builder.maxXactId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.maxXactId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun maxXactId(): Optional = - Optional.ofNullable(maxXactId.getNullable("max_xact_id")) + fun maxXactId(maxXactId: JsonField) = apply { body.maxXactId(maxXactId) } /** * Retrieve a snapshot of events from a past time * * The version id is essentially a filter on the latest event transaction id. You can use * the `max_xact_id` returned by a past fetch as the version to reproduce that exact fetch. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). */ - fun version(): Optional = Optional.ofNullable(version.getNullable("version")) + fun version(version: String?) = apply { body.version(version) } - /** - * Returns the raw JSON value of [cursor]. - * - * Unlike [cursor], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("cursor") @ExcludeMissing fun _cursor(): JsonField = cursor + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) /** - * Returns the raw JSON value of [limit]. + * Sets [Builder.version] to an arbitrary JSON value. * - * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.version] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit + fun version(version: JsonField) = apply { body.version(version) } - /** - * Returns the raw JSON value of [maxRootSpanId]. - * - * Unlike [maxRootSpanId], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("max_root_span_id") - @ExcludeMissing - fun _maxRootSpanId(): JsonField = maxRootSpanId + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - /** - * Returns the raw JSON value of [maxXactId]. - * - * Unlike [maxXactId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("max_xact_id") @ExcludeMissing fun _maxXactId(): JsonField = maxXactId + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - /** - * Returns the raw JSON value of [version]. - * - * Unlike [version], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - private var validated: Boolean = false + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - fun validate(): Body = apply { - if (validated) { - return@apply - } + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - cursor() - limit() - maxRootSpanId() - maxXactId() - version() - validated = true + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun toBuilder() = Builder().from(this) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - companion object { + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** Returns a mutable builder for constructing an instance of [Body]. */ - @JvmStatic fun builder() = Builder() + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - private var cursor: JsonField = JsonMissing.of() - private var limit: JsonField = JsonMissing.of() - private var maxRootSpanId: JsonField = JsonMissing.of() - private var maxXactId: JsonField = JsonMissing.of() - private var version: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - @JvmSynthetic - internal fun from(body: Body) = apply { - cursor = body.cursor - limit = body.limit - maxRootSpanId = body.maxRootSpanId - maxXactId = body.maxXactId - version = body.version - additionalProperties = body.additionalProperties.toMutableMap() - } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** - * An opaque string to be used as a cursor for the next page of results, in order from - * latest to earliest. - * - * The string can be obtained directly from the `cursor` property of the previous fetch - * query - */ - fun cursor(cursor: String?) = cursor(JsonField.ofNullable(cursor)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ - fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.cursor] to an arbitrary JSON value. - * - * You should usually call [Builder.cursor] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun cursor(cursor: JsonField) = apply { this.cursor = cursor } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - /** - * limit the number of traces fetched - * - * Fetch queries may be paginated if the total result size is expected to be large (e.g. - * project_logs which accumulate over a long time). Note that fetch queries only support - * pagination in descending time order (from latest to earliest `_xact_id`. Furthermore, - * later pages may return rows which showed up in earlier pages, except with an earlier - * `_xact_id`. This happens because pagination occurs over the whole version history of - * the event log. You will most likely want to exclude any such duplicate, outdated rows - * (by `id`) from your combined result set. - * - * The `limit` parameter controls the number of full traces to return. So you may end up - * with more individual rows than the specified limit if you are fetching events - * containing traces. - */ - fun limit(limit: Long?) = limit(JsonField.ofNullable(limit)) - - /** - * Alias for [Builder.limit]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun limit(limit: Long) = limit(limit as Long?) - - /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ - fun limit(limit: Optional) = limit(limit.getOrNull()) - - /** - * Sets [Builder.limit] to an arbitrary JSON value. - * - * You should usually call [Builder.limit] with a well-typed [Long] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun limit(limit: JsonField) = apply { this.limit = limit } - - /** - * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor - * of the explicit 'cursor' returned by object fetch requests. Please prefer the - * 'cursor' argument going forwards. - * - * Together, `max_xact_id` and `max_root_span_id` form a pagination cursor - * - * Since a paginated fetch query returns results in order from latest to earliest, the - * cursor for the next page can be found as the row with the minimum (earliest) value of - * the tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an - * overview of paginating fetch queries. - */ - fun maxRootSpanId(maxRootSpanId: String?) = - maxRootSpanId(JsonField.ofNullable(maxRootSpanId)) - - /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ - fun maxRootSpanId(maxRootSpanId: Optional) = - maxRootSpanId(maxRootSpanId.getOrNull()) - - /** - * Sets [Builder.maxRootSpanId] to an arbitrary JSON value. - * - * You should usually call [Builder.maxRootSpanId] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun maxRootSpanId(maxRootSpanId: JsonField) = apply { - this.maxRootSpanId = maxRootSpanId - } - - /** - * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor - * of the explicit 'cursor' returned by object fetch requests. Please prefer the - * 'cursor' argument going forwards. - * - * Together, `max_xact_id` and `max_root_span_id` form a pagination cursor - * - * Since a paginated fetch query returns results in order from latest to earliest, the - * cursor for the next page can be found as the row with the minimum (earliest) value of - * the tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an - * overview of paginating fetch queries. - */ - fun maxXactId(maxXactId: String?) = maxXactId(JsonField.ofNullable(maxXactId)) - - /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ - fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) - - /** - * Sets [Builder.maxXactId] to an arbitrary JSON value. - * - * You should usually call [Builder.maxXactId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun maxXactId(maxXactId: JsonField) = apply { this.maxXactId = maxXactId } - - /** - * Retrieve a snapshot of events from a past time - * - * The version id is essentially a filter on the latest event transaction id. You can - * use the `max_xact_id` returned by a past fetch as the version to reproduce that exact - * fetch. - */ - fun version(version: String?) = version(JsonField.ofNullable(version)) - - /** Alias for calling [Builder.version] with `version.orElse(null)`. */ - fun version(version: Optional) = version(version.getOrNull()) - - /** - * Sets [Builder.version] to an arbitrary JSON value. - * - * You should usually call [Builder.version] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun version(version: JsonField) = apply { this.version = version } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Body = - Body( - cursor, - limit, - maxRootSpanId, - maxXactId, - version, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && cursor == other.cursor && limit == other.limit && maxRootSpanId == other.maxRootSpanId && maxXactId == other.maxXactId && version == other.version && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(cursor, limit, maxRootSpanId, maxXactId, version, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{cursor=$cursor, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [ExperimentFetchPostParams]. + * Returns an immutable instance of [ExperimentFetchPostParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java * .experimentId() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): ExperimentFetchPostParams = + ExperimentFetchPostParams( + checkRequired("experimentId", experimentId), + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [ExperimentFetchPostParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var experimentId: String? = null - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + fun _body(): Body = body - @JvmSynthetic - internal fun from(experimentFetchPostParams: ExperimentFetchPostParams) = apply { - experimentId = experimentFetchPostParams.experimentId - body = experimentFetchPostParams.body.toBuilder() - additionalHeaders = experimentFetchPostParams.additionalHeaders.toBuilder() - additionalQueryParams = experimentFetchPostParams.additionalQueryParams.toBuilder() + fun _pathParam(index: Int): String = + when (index) { + 0 -> experimentId + else -> "" } - /** Experiment id */ - fun experimentId(experimentId: String) = apply { this.experimentId = experimentId } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val cursor: JsonField, + private val limit: JsonField, + private val maxRootSpanId: JsonField, + private val maxXactId: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("cursor") @ExcludeMissing cursor: JsonField = JsonMissing.of(), + @JsonProperty("limit") @ExcludeMissing limit: JsonField = JsonMissing.of(), + @JsonProperty("max_root_span_id") + @ExcludeMissing + maxRootSpanId: JsonField = JsonMissing.of(), + @JsonProperty("max_xact_id") + @ExcludeMissing + maxXactId: JsonField = JsonMissing.of(), + @JsonProperty("version") @ExcludeMissing version: JsonField = JsonMissing.of(), + ) : this(cursor, limit, maxRootSpanId, maxXactId, version, mutableMapOf()) /** * An opaque string to be used as a cursor for the next page of results, in order from @@ -582,19 +508,11 @@ private constructor( * * The string can be obtained directly from the `cursor` property of the previous fetch * query - */ - fun cursor(cursor: String?) = apply { body.cursor(cursor) } - - /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ - fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) - - /** - * Sets [Builder.cursor] to an arbitrary JSON value. * - * You should usually call [Builder.cursor] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun cursor(cursor: JsonField) = apply { body.cursor(cursor) } + fun cursor(): Optional = cursor.getOptional("cursor") /** * limit the number of traces fetched @@ -610,26 +528,11 @@ private constructor( * The `limit` parameter controls the number of full traces to return. So you may end up * with more individual rows than the specified limit if you are fetching events containing * traces. - */ - fun limit(limit: Long?) = apply { body.limit(limit) } - - /** - * Alias for [Builder.limit]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun limit(limit: Long) = limit(limit as Long?) - - /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ - fun limit(limit: Optional) = limit(limit.getOrNull()) - - /** - * Sets [Builder.limit] to an arbitrary JSON value. * - * You should usually call [Builder.limit] with a well-typed [Long] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun limit(limit: JsonField) = apply { body.limit(limit) } + fun limit(): Optional = limit.getOptional("limit") /** * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor of @@ -642,23 +545,11 @@ private constructor( * cursor for the next page can be found as the row with the minimum (earliest) value of the * tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an overview of * paginating fetch queries. - */ - fun maxRootSpanId(maxRootSpanId: String?) = apply { body.maxRootSpanId(maxRootSpanId) } - - /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ - fun maxRootSpanId(maxRootSpanId: Optional) = - maxRootSpanId(maxRootSpanId.getOrNull()) - - /** - * Sets [Builder.maxRootSpanId] to an arbitrary JSON value. * - * You should usually call [Builder.maxRootSpanId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun maxRootSpanId(maxRootSpanId: JsonField) = apply { - body.maxRootSpanId(maxRootSpanId) - } + fun maxRootSpanId(): Optional = maxRootSpanId.getOptional("max_root_span_id") /** * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor of @@ -671,176 +562,321 @@ private constructor( * cursor for the next page can be found as the row with the minimum (earliest) value of the * tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an overview of * paginating fetch queries. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun maxXactId(maxXactId: String?) = apply { body.maxXactId(maxXactId) } + fun maxXactId(): Optional = maxXactId.getOptional("max_xact_id") - /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ - fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) + /** + * Retrieve a snapshot of events from a past time + * + * The version id is essentially a filter on the latest event transaction id. You can use + * the `max_xact_id` returned by a past fetch as the version to reproduce that exact fetch. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun version(): Optional = version.getOptional("version") /** - * Sets [Builder.maxXactId] to an arbitrary JSON value. + * Returns the raw JSON value of [cursor]. * - * You should usually call [Builder.maxXactId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [cursor], this method doesn't throw if the JSON field has an unexpected type. */ - fun maxXactId(maxXactId: JsonField) = apply { body.maxXactId(maxXactId) } + @JsonProperty("cursor") @ExcludeMissing fun _cursor(): JsonField = cursor /** - * Retrieve a snapshot of events from a past time + * Returns the raw JSON value of [limit]. * - * The version id is essentially a filter on the latest event transaction id. You can use - * the `max_xact_id` returned by a past fetch as the version to reproduce that exact fetch. + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. */ - fun version(version: String?) = apply { body.version(version) } + @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit - /** Alias for calling [Builder.version] with `version.orElse(null)`. */ - fun version(version: Optional) = version(version.getOrNull()) + /** + * Returns the raw JSON value of [maxRootSpanId]. + * + * Unlike [maxRootSpanId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("max_root_span_id") + @ExcludeMissing + fun _maxRootSpanId(): JsonField = maxRootSpanId /** - * Sets [Builder.version] to an arbitrary JSON value. + * Returns the raw JSON value of [maxXactId]. * - * You should usually call [Builder.version] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [maxXactId], this method doesn't throw if the JSON field has an unexpected type. */ - fun version(version: JsonField) = apply { body.version(version) } + @JsonProperty("max_xact_id") @ExcludeMissing fun _maxXactId(): JsonField = maxXactId - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) - } + /** + * Returns the raw JSON value of [version]. + * + * Unlike [version], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) - } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + fun toBuilder() = Builder().from(this) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + companion object { - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** A builder for [Body]. */ + class Builder internal constructor() { - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + private var cursor: JsonField = JsonMissing.of() + private var limit: JsonField = JsonMissing.of() + private var maxRootSpanId: JsonField = JsonMissing.of() + private var maxXactId: JsonField = JsonMissing.of() + private var version: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + @JvmSynthetic + internal fun from(body: Body) = apply { + cursor = body.cursor + limit = body.limit + maxRootSpanId = body.maxRootSpanId + maxXactId = body.maxXactId + version = body.version + additionalProperties = body.additionalProperties.toMutableMap() + } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * An opaque string to be used as a cursor for the next page of results, in order from + * latest to earliest. + * + * The string can be obtained directly from the `cursor` property of the previous fetch + * query + */ + fun cursor(cursor: String?) = cursor(JsonField.ofNullable(cursor)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ + fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.cursor] to an arbitrary JSON value. + * + * You should usually call [Builder.cursor] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun cursor(cursor: JsonField) = apply { this.cursor = cursor } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** + * limit the number of traces fetched + * + * Fetch queries may be paginated if the total result size is expected to be large (e.g. + * project_logs which accumulate over a long time). Note that fetch queries only support + * pagination in descending time order (from latest to earliest `_xact_id`. Furthermore, + * later pages may return rows which showed up in earlier pages, except with an earlier + * `_xact_id`. This happens because pagination occurs over the whole version history of + * the event log. You will most likely want to exclude any such duplicate, outdated rows + * (by `id`) from your combined result set. + * + * The `limit` parameter controls the number of full traces to return. So you may end up + * with more individual rows than the specified limit if you are fetching events + * containing traces. + */ + fun limit(limit: Long?) = limit(JsonField.ofNullable(limit)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun limit(limit: Long) = limit(limit as Long?) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + /** + * Sets [Builder.limit] to an arbitrary JSON value. + * + * You should usually call [Builder.limit] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun limit(limit: JsonField) = apply { this.limit = limit } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + /** + * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor + * of the explicit 'cursor' returned by object fetch requests. Please prefer the + * 'cursor' argument going forwards. + * + * Together, `max_xact_id` and `max_root_span_id` form a pagination cursor + * + * Since a paginated fetch query returns results in order from latest to earliest, the + * cursor for the next page can be found as the row with the minimum (earliest) value of + * the tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an + * overview of paginating fetch queries. + */ + fun maxRootSpanId(maxRootSpanId: String?) = + maxRootSpanId(JsonField.ofNullable(maxRootSpanId)) - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ + fun maxRootSpanId(maxRootSpanId: Optional) = + maxRootSpanId(maxRootSpanId.getOrNull()) - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** + * Sets [Builder.maxRootSpanId] to an arbitrary JSON value. + * + * You should usually call [Builder.maxRootSpanId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxRootSpanId(maxRootSpanId: JsonField) = apply { + this.maxRootSpanId = maxRootSpanId + } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + /** + * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor + * of the explicit 'cursor' returned by object fetch requests. Please prefer the + * 'cursor' argument going forwards. + * + * Together, `max_xact_id` and `max_root_span_id` form a pagination cursor + * + * Since a paginated fetch query returns results in order from latest to earliest, the + * cursor for the next page can be found as the row with the minimum (earliest) value of + * the tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an + * overview of paginating fetch queries. + */ + fun maxXactId(maxXactId: String?) = maxXactId(JsonField.ofNullable(maxXactId)) - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ + fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + /** + * Sets [Builder.maxXactId] to an arbitrary JSON value. + * + * You should usually call [Builder.maxXactId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxXactId(maxXactId: JsonField) = apply { this.maxXactId = maxXactId } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + /** + * Retrieve a snapshot of events from a past time + * + * The version id is essentially a filter on the latest event transaction id. You can + * use the `max_xact_id` returned by a past fetch as the version to reproduce that exact + * fetch. + */ + fun version(version: String?) = version(JsonField.ofNullable(version)) + + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) + + /** + * Sets [Builder.version] to an arbitrary JSON value. + * + * You should usually call [Builder.version] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun version(version: JsonField) = apply { this.version = version } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body( + cursor, + limit, + maxRootSpanId, + maxXactId, + version, + additionalProperties.toMutableMap(), + ) + } - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + cursor() + limit() + maxRootSpanId() + maxXactId() + version() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + /** - * Returns an immutable instance of [ExperimentFetchPostParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * The following fields are required: - * ```java - * .experimentId() - * ``` - * - * @throws IllegalStateException if any required field is unset. + * Used for best match union deserialization. */ - fun build(): ExperimentFetchPostParams = - ExperimentFetchPostParams( - checkRequired("experimentId", experimentId), - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + @JvmSynthetic + internal fun validity(): Int = + (if (cursor.asKnown().isPresent) 1 else 0) + + (if (limit.asKnown().isPresent) 1 else 0) + + (if (maxRootSpanId.asKnown().isPresent) 1 else 0) + + (if (maxXactId.asKnown().isPresent) 1 else 0) + + (if (version.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && cursor == other.cursor && limit == other.limit && maxRootSpanId == other.maxRootSpanId && maxXactId == other.maxXactId && version == other.version && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(cursor, limit, maxRootSpanId, maxXactId, version, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{cursor=$cursor, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentInsertParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentInsertParams.kt index 16a00bbe..2112cf67 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentInsertParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentInsertParams.kt @@ -6,20 +6,20 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 kotlin.jvm.optionals.getOrNull /** Insert a set of events into the experiment */ class ExperimentInsertParams @@ -54,170 +54,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> experimentId - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("events") - @ExcludeMissing - private val events: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * A list of experiment events to insert - * - * @throws BraintrustInvalidDataException 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 events(): List = events.getRequired("events") - - /** - * Returns the raw JSON value of [events]. - * - * Unlike [events], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("events") - @ExcludeMissing - fun _events(): JsonField> = events - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - events().forEach { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .events() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var events: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - events = body.events.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** A list of experiment events to insert */ - fun events(events: List) = events(JsonField.of(events)) - - /** - * Sets [Builder.events] to an arbitrary JSON value. - * - * You should usually call [Builder.events] with a well-typed - * `List` value instead. This method is primarily for setting the - * field to an undocumented or not yet supported value. - */ - fun events(events: JsonField>) = apply { - this.events = events.map { it.toMutableList() } - } - - /** - * Adds a single [InsertExperimentEvent] to [events]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addEvent(event: InsertExperimentEvent) = apply { - events = - (events ?: JsonField.of(mutableListOf())).also { - checkKnown("events", it).add(event) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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 - * .events() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("events", events).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && events == other.events && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(events, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Body{events=$events, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -235,7 +71,6 @@ private constructor( } /** A builder for [ExperimentInsertParams]. */ - @NoAutoDetect class Builder internal constructor() { private var experimentId: String? = null @@ -254,6 +89,15 @@ private constructor( /** Experiment id */ fun experimentId(experimentId: String) = apply { this.experimentId = experimentId } + /** + * 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: + * - [events] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** A list of experiment events to insert */ fun events(events: List) = apply { body.events(events) } @@ -412,6 +256,195 @@ private constructor( ) } + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> experimentId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val events: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("events") + @ExcludeMissing + events: JsonField> = JsonMissing.of() + ) : this(events, mutableMapOf()) + + /** + * A list of experiment events to insert + * + * @throws BraintrustInvalidDataException 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 events(): List = events.getRequired("events") + + /** + * Returns the raw JSON value of [events]. + * + * Unlike [events], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("events") + @ExcludeMissing + fun _events(): JsonField> = events + + @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 + * .events() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var events: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + events = body.events.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** A list of experiment events to insert */ + fun events(events: List) = events(JsonField.of(events)) + + /** + * Sets [Builder.events] to an arbitrary JSON value. + * + * You should usually call [Builder.events] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun events(events: JsonField>) = apply { + this.events = events.map { it.toMutableList() } + } + + /** + * Adds a single [InsertExperimentEvent] to [events]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addEvent(event: InsertExperimentEvent) = apply { + events = + (events ?: JsonField.of(mutableListOf())).also { + checkKnown("events", it).add(event) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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 + * .events() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("events", events).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + events().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (events.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && events == other.events && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(events, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = "Body{events=$events, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListPage.kt index 3c803f0b..64e38158 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListPage.kt @@ -2,171 +2,115 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.ExperimentService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all experiments. The experiments are sorted by creation date, with the most - * recently-created experiments coming first - */ +/** @see [ExperimentService.list] */ class ExperimentListPage private constructor( - private val experimentsService: ExperimentService, + private val service: ExperimentService, private val params: ExperimentListParams, - private val response: Response, + private val response: ExperimentListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [ExperimentListPageResponse], but gracefully handles missing data. + * + * @see [ExperimentListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ExperimentListPage && experimentsService == other.experimentsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(experimentsService, params, response) /* spotless:on */ - - override fun toString() = - "ExperimentListPage{experimentsService=$experimentsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - ExperimentListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - ExperimentListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { experimentsService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of( - experimentsService: ExperimentService, - params: ExperimentListParams, - response: Response, - ) = ExperimentListPage(experimentsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") - private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): ExperimentListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): ExperimentListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [ExperimentListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [ExperimentListPage]. */ + class Builder internal constructor() { - companion object { + private var service: ExperimentService? = null + private var params: ExperimentListParams? = null + private var response: ExperimentListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [ExperimentListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(experimentListPage: ExperimentListPage) = apply { + service = experimentListPage.service + params = experimentListPage.params + response = experimentListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: ExperimentService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: ExperimentListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ExperimentListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ExperimentListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ExperimentListPage = + ExperimentListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: ExperimentListPage) : Iterable { @@ -187,4 +131,17 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ExperimentListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "ExperimentListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListPageAsync.kt index cfdcebc5..b8b5c33d 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListPageAsync.kt @@ -2,175 +2,119 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.ExperimentServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all experiments. The experiments are sorted by creation date, with the most - * recently-created experiments coming first - */ +/** @see [ExperimentServiceAsync.list] */ class ExperimentListPageAsync private constructor( - private val experimentsService: ExperimentServiceAsync, + private val service: ExperimentServiceAsync, private val params: ExperimentListParams, - private val response: Response, + private val response: ExperimentListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [ExperimentListPageResponse], but gracefully handles missing data. + * + * @see [ExperimentListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ExperimentListPageAsync && experimentsService == other.experimentsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(experimentsService, params, response) /* spotless:on */ - - override fun toString() = - "ExperimentListPageAsync{experimentsService=$experimentsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - ExperimentListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - ExperimentListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { experimentsService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of( - experimentsService: ExperimentServiceAsync, - params: ExperimentListParams, - response: Response, - ) = ExperimentListPageAsync(experimentsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") - private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): ExperimentListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): ExperimentListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [ExperimentListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [ExperimentListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: ExperimentServiceAsync? = null + private var params: ExperimentListParams? = null + private var response: ExperimentListPageResponse? = null - /** - * Returns a mutable builder for constructing an instance of [ExperimentListPageAsync]. - */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(experimentListPageAsync: ExperimentListPageAsync) = apply { + service = experimentListPageAsync.service + params = experimentListPageAsync.params + response = experimentListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: ExperimentServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: ExperimentListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ExperimentListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ExperimentListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ExperimentListPageAsync = + ExperimentListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: ExperimentListPageAsync) { @@ -198,4 +142,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ExperimentListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "ExperimentListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListPageResponse.kt new file mode 100644 index 00000000..ae4bfd1c --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListPageResponse.kt @@ -0,0 +1,194 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class ExperimentListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") + @ExcludeMissing + objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of experiment objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [ExperimentListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ExperimentListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(experimentListPageResponse: ExperimentListPageResponse) = apply { + objects = experimentListPageResponse.objects.map { it.toMutableList() } + additionalProperties = experimentListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of experiment objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [Experiment] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: Experiment) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ExperimentListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ExperimentListPageResponse = + ExperimentListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ExperimentListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ExperimentListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ExperimentListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListParams.kt index 6e2f5bef..29c78e5b 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListParams.kt @@ -2,22 +2,10 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -83,33 +71,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - endingBefore?.let { put("ending_before", it) } - experimentName?.let { put("experiment_name", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - orgName?.let { put("org_name", it) } - projectId?.let { put("project_id", it) } - projectName?.let { put("project_name", it) } - startingAfter?.let { put("starting_after", it) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -121,7 +82,6 @@ private constructor( } /** A builder for [ExperimentListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var endingBefore: String? = null @@ -345,17 +305,41 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + endingBefore?.let { put("ending_before", it) } + experimentName?.let { put("experiment_name", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + orgName?.let { put("org_name", it) } + projectId?.let { put("project_id", it) } + projectName?.let { put("project_name", it) } + startingAfter?.let { put("starting_after", it) } + putAll(additionalQueryParams) + } + .build() + /** * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -370,15 +354,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -394,7 +375,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -411,51 +391,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentRetrieveParams.kt index 54ba50ec..6b7a9da3 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> experimentId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [ExperimentRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var experimentId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> experimentId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentSummarizeParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentSummarizeParams.kt index 10cf6fc7..3b4de8f0 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentSummarizeParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentSummarizeParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -41,24 +40,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - comparisonExperimentId?.let { put("comparison_experiment_id", it) } - summarizeScores?.let { put("summarize_scores", it.toString()) } - putAll(additionalQueryParams) - } - .build() - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> experimentId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -75,7 +56,6 @@ private constructor( } /** A builder for [ExperimentSummarizeParams]. */ - @NoAutoDetect class Builder internal constructor() { private var experimentId: String? = null @@ -252,6 +232,23 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> experimentId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + comparisonExperimentId?.let { put("comparison_experiment_id", it) } + summarizeScores?.let { put("summarize_scores", it.toString()) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentUpdateParams.kt index 74a29345..75600e2e 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentUpdateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentUpdateParams.kt @@ -6,18 +6,17 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -166,219 +165,540 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) - override fun _headers(): Headers = additionalHeaders + companion object { - override fun _queryParams(): QueryParams = additionalQueryParams + /** + * Returns a mutable builder for constructing an instance of [ExperimentUpdateParams]. + * + * The following fields are required: + * ```java + * .experimentId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - fun getPathParam(index: Int): String { - return when (index) { - 0 -> experimentId - else -> "" + /** A builder for [ExperimentUpdateParams]. */ + class Builder internal constructor() { + + private var experimentId: 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(experimentUpdateParams: ExperimentUpdateParams) = apply { + experimentId = experimentUpdateParams.experimentId + body = experimentUpdateParams.body.toBuilder() + additionalHeaders = experimentUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = experimentUpdateParams.additionalQueryParams.toBuilder() } - } - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("base_exp_id") - @ExcludeMissing - private val baseExpId: JsonField = JsonMissing.of(), - @JsonProperty("dataset_id") - @ExcludeMissing - private val datasetId: JsonField = JsonMissing.of(), - @JsonProperty("dataset_version") - @ExcludeMissing - private val datasetVersion: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("public") - @ExcludeMissing - private val public_: JsonField = JsonMissing.of(), - @JsonProperty("repo_info") - @ExcludeMissing - private val repoInfo: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** Experiment id */ + fun experimentId(experimentId: String) = apply { this.experimentId = experimentId } /** - * Id of default base experiment to compare against when viewing this experiment + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [baseExpId] + * - [datasetId] + * - [datasetVersion] + * - [description] + * - [metadata] + * - etc. */ - fun baseExpId(): Optional = - Optional.ofNullable(baseExpId.getNullable("base_exp_id")) + fun body(body: Body) = apply { this.body = body.toBuilder() } - /** - * Identifier of the linked dataset, or null if the experiment is not linked to a dataset - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun datasetId(): Optional = Optional.ofNullable(datasetId.getNullable("dataset_id")) + /** Id of default base experiment to compare against when viewing this experiment */ + fun baseExpId(baseExpId: String?) = apply { body.baseExpId(baseExpId) } - /** - * Version number of the linked dataset the experiment was run against. This can be used to - * reproduce the experiment after the dataset has been modified. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun datasetVersion(): Optional = - Optional.ofNullable(datasetVersion.getNullable("dataset_version")) + /** Alias for calling [Builder.baseExpId] with `baseExpId.orElse(null)`. */ + fun baseExpId(baseExpId: Optional) = baseExpId(baseExpId.getOrNull()) /** - * Textual description of the experiment + * Sets [Builder.baseExpId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.baseExpId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun baseExpId(baseExpId: JsonField) = apply { body.baseExpId(baseExpId) } /** - * User-controlled metadata about the experiment - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * Identifier of the linked dataset, or null if the experiment is not linked to a dataset */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun datasetId(datasetId: String?) = apply { body.datasetId(datasetId) } - /** - * Name of the experiment. Within a project, experiment names are unique - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ + fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) /** - * Whether or not the experiment is public. Public experiments can be viewed by anybody - * inside or outside the organization + * Sets [Builder.datasetId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.datasetId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun public_(): Optional = Optional.ofNullable(public_.getNullable("public")) + fun datasetId(datasetId: JsonField) = apply { body.datasetId(datasetId) } /** - * Metadata about the state of the repo when the experiment was created - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * Version number of the linked dataset the experiment was run against. This can be used to + * reproduce the experiment after the dataset has been modified. */ - fun repoInfo(): Optional = Optional.ofNullable(repoInfo.getNullable("repo_info")) + fun datasetVersion(datasetVersion: String?) = apply { body.datasetVersion(datasetVersion) } + + /** Alias for calling [Builder.datasetVersion] with `datasetVersion.orElse(null)`. */ + fun datasetVersion(datasetVersion: Optional) = + datasetVersion(datasetVersion.getOrNull()) /** - * Returns the raw JSON value of [baseExpId]. + * Sets [Builder.datasetVersion] to an arbitrary JSON value. * - * Unlike [baseExpId], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.datasetVersion] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("base_exp_id") @ExcludeMissing fun _baseExpId(): JsonField = baseExpId + fun datasetVersion(datasetVersion: JsonField) = apply { + body.datasetVersion(datasetVersion) + } + + /** Textual description of the experiment */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) /** - * Returns the raw JSON value of [datasetId]. + * Sets [Builder.description] to an arbitrary JSON value. * - * Unlike [datasetId], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("dataset_id") @ExcludeMissing fun _datasetId(): JsonField = datasetId + fun description(description: JsonField) = apply { body.description(description) } + + /** User-controlled metadata about the experiment */ + fun metadata(metadata: Metadata?) = apply { body.metadata(metadata) } + + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) /** - * Returns the raw JSON value of [datasetVersion]. + * Sets [Builder.metadata] to an arbitrary JSON value. * - * Unlike [datasetVersion], this method doesn't throw if the JSON field has an unexpected - * type. + * 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. */ - @JsonProperty("dataset_version") - @ExcludeMissing - fun _datasetVersion(): JsonField = datasetVersion + fun metadata(metadata: JsonField) = apply { body.metadata(metadata) } + + /** Name of the experiment. Within a project, experiment names are unique */ + fun name(name: String?) = apply { body.name(name) } + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) /** - * Returns the raw JSON value of [description]. + * Sets [Builder.name] to an arbitrary JSON value. * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description + fun name(name: JsonField) = apply { body.name(name) } /** - * Returns the raw JSON value of [metadata]. - * - * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + * Whether or not the experiment is public. Public experiments can be viewed by anybody + * inside or outside the organization */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + fun public_(public_: Boolean?) = apply { body.public_(public_) } /** - * Returns the raw JSON value of [name]. + * Alias for [Builder.public_]. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * This unboxed primitive overload exists for backwards compatibility. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun public_(public_: Boolean) = public_(public_ as Boolean?) + + /** Alias for calling [Builder.public_] with `public_.orElse(null)`. */ + fun public_(public_: Optional) = public_(public_.getOrNull()) /** - * Returns the raw JSON value of [public_]. + * Sets [Builder.public_] to an arbitrary JSON value. * - * Unlike [public_], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.public_] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("public") @ExcludeMissing fun _public_(): JsonField = public_ + fun public_(public_: JsonField) = apply { body.public_(public_) } + + /** Metadata about the state of the repo when the experiment was created */ + fun repoInfo(repoInfo: RepoInfo?) = apply { body.repoInfo(repoInfo) } + + /** Alias for calling [Builder.repoInfo] with `repoInfo.orElse(null)`. */ + fun repoInfo(repoInfo: Optional) = repoInfo(repoInfo.getOrNull()) /** - * Returns the raw JSON value of [repoInfo]. + * Sets [Builder.repoInfo] to an arbitrary JSON value. * - * Unlike [repoInfo], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.repoInfo] with a well-typed [RepoInfo] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("repo_info") @ExcludeMissing fun _repoInfo(): JsonField = repoInfo + fun repoInfo(repoInfo: JsonField) = apply { body.repoInfo(repoInfo) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var validated: Boolean = false + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - fun validate(): Body = apply { - if (validated) { - return@apply + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - baseExpId() - datasetId() - datasetVersion() - description() - metadata().ifPresent { it.validate() } - name() - public_() - repoInfo().ifPresent { it.validate() } - validated = true + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - fun toBuilder() = Builder().from(this) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - companion object { + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Returns a mutable builder for constructing an instance of [Body]. */ - @JvmStatic fun builder() = Builder() + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - private var baseExpId: JsonField = JsonMissing.of() - private var datasetId: JsonField = JsonMissing.of() - private var datasetVersion: JsonField = JsonMissing.of() - private var description: JsonField = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() + 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 [ExperimentUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .experimentId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ExperimentUpdateParams = + ExperimentUpdateParams( + checkRequired("experimentId", experimentId), + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> experimentId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val baseExpId: JsonField, + private val datasetId: JsonField, + private val datasetVersion: JsonField, + private val description: JsonField, + private val metadata: JsonField, + private val name: JsonField, + private val public_: JsonField, + private val repoInfo: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("base_exp_id") + @ExcludeMissing + baseExpId: JsonField = JsonMissing.of(), + @JsonProperty("dataset_id") + @ExcludeMissing + datasetId: JsonField = JsonMissing.of(), + @JsonProperty("dataset_version") + @ExcludeMissing + datasetVersion: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("public") @ExcludeMissing public_: JsonField = JsonMissing.of(), + @JsonProperty("repo_info") + @ExcludeMissing + repoInfo: JsonField = JsonMissing.of(), + ) : this( + baseExpId, + datasetId, + datasetVersion, + description, + metadata, + name, + public_, + repoInfo, + mutableMapOf(), + ) + + /** + * Id of default base experiment to compare against when viewing this experiment + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseExpId(): Optional = baseExpId.getOptional("base_exp_id") + + /** + * Identifier of the linked dataset, or null if the experiment is not linked to a dataset + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun datasetId(): Optional = datasetId.getOptional("dataset_id") + + /** + * Version number of the linked dataset the experiment was run against. This can be used to + * reproduce the experiment after the dataset has been modified. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun datasetVersion(): Optional = datasetVersion.getOptional("dataset_version") + + /** + * Textual description of the experiment + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * User-controlled metadata about the experiment + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * Name of the experiment. Within a project, experiment names are unique + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Whether or not the experiment is public. Public experiments can be viewed by anybody + * inside or outside the organization + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun public_(): Optional = public_.getOptional("public") + + /** + * Metadata about the state of the repo when the experiment was created + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun repoInfo(): Optional = repoInfo.getOptional("repo_info") + + /** + * Returns the raw JSON value of [baseExpId]. + * + * Unlike [baseExpId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("base_exp_id") @ExcludeMissing fun _baseExpId(): JsonField = baseExpId + + /** + * Returns the raw JSON value of [datasetId]. + * + * Unlike [datasetId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("dataset_id") @ExcludeMissing fun _datasetId(): JsonField = datasetId + + /** + * Returns the raw JSON value of [datasetVersion]. + * + * Unlike [datasetVersion], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("dataset_version") + @ExcludeMissing + fun _datasetVersion(): JsonField = datasetVersion + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [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 [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 [public_]. + * + * Unlike [public_], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("public") @ExcludeMissing fun _public_(): JsonField = public_ + + /** + * Returns the raw JSON value of [repoInfo]. + * + * Unlike [repoInfo], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("repo_info") @ExcludeMissing fun _repoInfo(): JsonField = repoInfo + + @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]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var baseExpId: JsonField = JsonMissing.of() + private var datasetId: JsonField = JsonMissing.of() + private var datasetVersion: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() private var name: JsonField = JsonMissing.of() private var public_: JsonField = JsonMissing.of() private var repoInfo: JsonField = JsonMissing.of() @@ -455,478 +775,201 @@ private constructor( /** Textual description of the experiment */ fun description(description: String?) = description(JsonField.ofNullable(description)) - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } - - /** User-controlled metadata about the experiment */ - 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 } - - /** Name of the experiment. Within a project, experiment names are unique */ - 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 } - - /** - * Whether or not the experiment is public. Public experiments can be viewed by anybody - * inside or outside the organization - */ - fun public_(public_: Boolean?) = public_(JsonField.ofNullable(public_)) - - /** - * Alias for [Builder.public_]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun public_(public_: Boolean) = public_(public_ as Boolean?) - - /** Alias for calling [Builder.public_] with `public_.orElse(null)`. */ - fun public_(public_: Optional) = public_(public_.getOrNull()) - - /** - * Sets [Builder.public_] to an arbitrary JSON value. - * - * You should usually call [Builder.public_] with a well-typed [Boolean] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun public_(public_: JsonField) = apply { this.public_ = public_ } - - /** Metadata about the state of the repo when the experiment was created */ - fun repoInfo(repoInfo: RepoInfo?) = repoInfo(JsonField.ofNullable(repoInfo)) - - /** Alias for calling [Builder.repoInfo] with `repoInfo.orElse(null)`. */ - fun repoInfo(repoInfo: Optional) = repoInfo(repoInfo.getOrNull()) - - /** - * Sets [Builder.repoInfo] to an arbitrary JSON value. - * - * You should usually call [Builder.repoInfo] with a well-typed [RepoInfo] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun repoInfo(repoInfo: JsonField) = apply { this.repoInfo = repoInfo } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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. - */ - fun build(): Body = - Body( - baseExpId, - datasetId, - datasetVersion, - description, - metadata, - name, - public_, - repoInfo, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && baseExpId == other.baseExpId && datasetId == other.datasetId && datasetVersion == other.datasetVersion && description == other.description && metadata == other.metadata && name == other.name && public_ == other.public_ && repoInfo == other.repoInfo && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(baseExpId, datasetId, datasetVersion, description, metadata, name, public_, repoInfo, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{baseExpId=$baseExpId, datasetId=$datasetId, datasetVersion=$datasetVersion, description=$description, metadata=$metadata, name=$name, public_=$public_, repoInfo=$repoInfo, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [ExperimentUpdateParams]. - * - * The following fields are required: - * ```java - * .experimentId() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ExperimentUpdateParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var experimentId: 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(experimentUpdateParams: ExperimentUpdateParams) = apply { - experimentId = experimentUpdateParams.experimentId - body = experimentUpdateParams.body.toBuilder() - additionalHeaders = experimentUpdateParams.additionalHeaders.toBuilder() - additionalQueryParams = experimentUpdateParams.additionalQueryParams.toBuilder() - } - - /** Experiment id */ - fun experimentId(experimentId: String) = apply { this.experimentId = experimentId } - - /** Id of default base experiment to compare against when viewing this experiment */ - fun baseExpId(baseExpId: String?) = apply { body.baseExpId(baseExpId) } - - /** Alias for calling [Builder.baseExpId] with `baseExpId.orElse(null)`. */ - fun baseExpId(baseExpId: Optional) = baseExpId(baseExpId.getOrNull()) - - /** - * Sets [Builder.baseExpId] to an arbitrary JSON value. - * - * You should usually call [Builder.baseExpId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun baseExpId(baseExpId: JsonField) = apply { body.baseExpId(baseExpId) } - - /** - * Identifier of the linked dataset, or null if the experiment is not linked to a dataset - */ - fun datasetId(datasetId: String?) = apply { body.datasetId(datasetId) } - - /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ - fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) - - /** - * Sets [Builder.datasetId] to an arbitrary JSON value. - * - * You should usually call [Builder.datasetId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun datasetId(datasetId: JsonField) = apply { body.datasetId(datasetId) } - - /** - * Version number of the linked dataset the experiment was run against. This can be used to - * reproduce the experiment after the dataset has been modified. - */ - fun datasetVersion(datasetVersion: String?) = apply { body.datasetVersion(datasetVersion) } - - /** Alias for calling [Builder.datasetVersion] with `datasetVersion.orElse(null)`. */ - fun datasetVersion(datasetVersion: Optional) = - datasetVersion(datasetVersion.getOrNull()) - - /** - * Sets [Builder.datasetVersion] to an arbitrary JSON value. - * - * You should usually call [Builder.datasetVersion] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun datasetVersion(datasetVersion: JsonField) = apply { - body.datasetVersion(datasetVersion) - } - - /** Textual description of the experiment */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun description(description: JsonField) = apply { body.description(description) } - - /** User-controlled metadata about the experiment */ - 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) } - - /** Name of the experiment. Within a project, experiment names are unique */ - fun name(name: String?) = apply { body.name(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 { body.name(name) } - - /** - * Whether or not the experiment is public. Public experiments can be viewed by anybody - * inside or outside the organization - */ - fun public_(public_: Boolean?) = apply { body.public_(public_) } - - /** - * Alias for [Builder.public_]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun public_(public_: Boolean) = public_(public_ as Boolean?) - - /** Alias for calling [Builder.public_] with `public_.orElse(null)`. */ - fun public_(public_: Optional) = public_(public_.getOrNull()) - - /** - * Sets [Builder.public_] to an arbitrary JSON value. - * - * You should usually call [Builder.public_] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun public_(public_: JsonField) = apply { body.public_(public_) } - - /** Metadata about the state of the repo when the experiment was created */ - fun repoInfo(repoInfo: RepoInfo?) = apply { body.repoInfo(repoInfo) } - - /** Alias for calling [Builder.repoInfo] with `repoInfo.orElse(null)`. */ - fun repoInfo(repoInfo: Optional) = repoInfo(repoInfo.getOrNull()) - - /** - * Sets [Builder.repoInfo] to an arbitrary JSON value. - * - * You should usually call [Builder.repoInfo] with a well-typed [RepoInfo] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun repoInfo(repoInfo: JsonField) = apply { body.repoInfo(repoInfo) } - - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) - } - - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description } - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** User-controlled metadata about the experiment */ + fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * 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 additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** Name of the experiment. Within a project, experiment names are unique */ + fun name(name: String?) = name(JsonField.ofNullable(name)) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * 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 putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Whether or not the experiment is public. Public experiments can be viewed by anybody + * inside or outside the organization + */ + fun public_(public_: Boolean?) = public_(JsonField.ofNullable(public_)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Alias for [Builder.public_]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun public_(public_: Boolean) = public_(public_ as Boolean?) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** Alias for calling [Builder.public_] with `public_.orElse(null)`. */ + fun public_(public_: Optional) = public_(public_.getOrNull()) - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** + * Sets [Builder.public_] to an arbitrary JSON value. + * + * You should usually call [Builder.public_] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun public_(public_: JsonField) = apply { this.public_ = public_ } - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Metadata about the state of the repo when the experiment was created */ + fun repoInfo(repoInfo: RepoInfo?) = repoInfo(JsonField.ofNullable(repoInfo)) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.repoInfo] with `repoInfo.orElse(null)`. */ + fun repoInfo(repoInfo: Optional) = repoInfo(repoInfo.getOrNull()) - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + /** + * Sets [Builder.repoInfo] to an arbitrary JSON value. + * + * You should usually call [Builder.repoInfo] with a well-typed [RepoInfo] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun repoInfo(repoInfo: JsonField) = apply { this.repoInfo = repoInfo } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body( + baseExpId, + datasetId, + datasetVersion, + description, + metadata, + name, + public_, + repoInfo, + additionalProperties.toMutableMap(), + ) } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) + baseExpId() + datasetId() + datasetVersion() + description() + metadata().ifPresent { it.validate() } + name() + public_() + repoInfo().ifPresent { it.validate() } + validated = true } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + /** + * Returns 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 (baseExpId.asKnown().isPresent) 1 else 0) + + (if (datasetId.asKnown().isPresent) 1 else 0) + + (if (datasetVersion.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (public_.asKnown().isPresent) 1 else 0) + + (repoInfo.asKnown().getOrNull()?.validity() ?: 0) - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + return /* spotless:off */ other is Body && baseExpId == other.baseExpId && datasetId == other.datasetId && datasetVersion == other.datasetVersion && description == other.description && metadata == other.metadata && name == other.name && public_ == other.public_ && repoInfo == other.repoInfo && additionalProperties == other.additionalProperties /* spotless:on */ } - /** - * Returns an immutable instance of [ExperimentUpdateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .experimentId() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): ExperimentUpdateParams = - ExperimentUpdateParams( - checkRequired("experimentId", experimentId), - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(baseExpId, datasetId, datasetVersion, description, metadata, name, public_, repoInfo, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{baseExpId=$baseExpId, datasetId=$datasetId, datasetVersion=$datasetVersion, description=$description, metadata=$metadata, name=$name, public_=$public_, repoInfo=$repoInfo, additionalProperties=$additionalProperties}" } /** User-controlled metadata about the experiment */ - @NoAutoDetect class Metadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -972,6 +1015,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackDatasetItem.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackDatasetItem.kt index 363314e1..9986ad76 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackDatasetItem.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackDatasetItem.kt @@ -7,40 +7,38 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 -@NoAutoDetect class FeedbackDatasetItem -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("comment") - @ExcludeMissing - private val comment: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("source") - @ExcludeMissing - private val source: JsonField = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val comment: JsonField, + private val metadata: JsonField, + private val source: JsonField, + private val tags: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("comment") @ExcludeMissing comment: JsonField = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("source") @ExcludeMissing source: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this(id, comment, metadata, source, tags, mutableMapOf()) + /** * The id of the dataset event to log feedback for. This is the row `id` returned by `POST * /v1/dataset/{dataset_id}/insert` @@ -56,7 +54,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun comment(): Optional = Optional.ofNullable(comment.getNullable("comment")) + fun comment(): Optional = comment.getOptional("comment") /** * A dictionary with additional data about the feedback. If you have a `user_id`, you can log it @@ -66,7 +64,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** * The source of the feedback. Must be one of "external" (default), "app", or "api" @@ -74,7 +72,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun source(): Optional = Optional.ofNullable(source.getNullable("source")) + fun source(): Optional = source.getOptional("source") /** * A list of tags to log @@ -82,7 +80,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [id]. @@ -119,24 +117,15 @@ private constructor( */ @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): FeedbackDatasetItem = apply { - if (validated) { - return@apply - } - - id() - comment() - metadata().ifPresent { it.validate() } - source() - tags() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -298,37 +287,62 @@ private constructor( metadata, source, (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): FeedbackDatasetItem = apply { + if (validated) { + return@apply + } + + id() + comment() + metadata().ifPresent { it.validate() } + source().ifPresent { it.validate() } + tags() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (comment.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (source.asKnown().getOrNull()?.validity() ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + /** * A dictionary with additional data about the feedback. If you have a `user_id`, you can log it * here and access it in the Braintrust UI. Note, this metadata does not correspond to the main * event itself, but rather the audit log attached to the event. */ - @NoAutoDetect class Metadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -374,6 +388,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -485,6 +527,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Source = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackExperimentItem.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackExperimentItem.kt index 406a2fd1..ef903e91 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackExperimentItem.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackExperimentItem.kt @@ -7,44 +7,42 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 -@NoAutoDetect class FeedbackExperimentItem -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("comment") - @ExcludeMissing - private val comment: JsonField = JsonMissing.of(), - @JsonProperty("expected") @ExcludeMissing private val expected: JsonValue = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("scores") - @ExcludeMissing - private val scores: JsonField = JsonMissing.of(), - @JsonProperty("source") - @ExcludeMissing - private val source: JsonField = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val comment: JsonField, + private val expected: JsonValue, + private val metadata: JsonField, + private val scores: JsonField, + private val source: JsonField, + private val tags: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("comment") @ExcludeMissing comment: JsonField = JsonMissing.of(), + @JsonProperty("expected") @ExcludeMissing expected: JsonValue = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("scores") @ExcludeMissing scores: JsonField = JsonMissing.of(), + @JsonProperty("source") @ExcludeMissing source: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this(id, comment, expected, metadata, scores, source, tags, mutableMapOf()) + /** * The id of the experiment event to log feedback for. This is the row `id` returned by `POST * /v1/experiment/{experiment_id}/insert` @@ -60,7 +58,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun comment(): Optional = Optional.ofNullable(comment.getNullable("comment")) + fun comment(): Optional = comment.getOptional("comment") /** * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to @@ -76,7 +74,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** * A dictionary of numeric values (between 0 and 1) to log. These scores will be merged into the @@ -85,7 +83,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun scores(): Optional = Optional.ofNullable(scores.getNullable("scores")) + fun scores(): Optional = scores.getOptional("scores") /** * The source of the feedback. Must be one of "external" (default), "app", or "api" @@ -93,7 +91,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun source(): Optional = Optional.ofNullable(source.getNullable("source")) + fun source(): Optional = source.getOptional("source") /** * A list of tags to log @@ -101,7 +99,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [id]. @@ -145,25 +143,15 @@ private constructor( */ @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): FeedbackExperimentItem = apply { - if (validated) { - return@apply - } - - id() - comment() - metadata().ifPresent { it.validate() } - scores().ifPresent { it.validate() } - source() - tags() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -354,37 +342,64 @@ private constructor( scores, source, (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): FeedbackExperimentItem = apply { + if (validated) { + return@apply + } + + id() + comment() + metadata().ifPresent { it.validate() } + scores().ifPresent { it.validate() } + source().ifPresent { it.validate() } + tags() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (comment.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (scores.asKnown().getOrNull()?.validity() ?: 0) + + (source.asKnown().getOrNull()?.validity() ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + /** * A dictionary with additional data about the feedback. If you have a `user_id`, you can log it * here and access it in the Braintrust UI. Note, this metadata does not correspond to the main * event itself, but rather the audit log attached to the event. */ - @NoAutoDetect class Metadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -430,6 +445,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -451,28 +494,17 @@ private constructor( * A dictionary of numeric values (between 0 and 1) to log. These scores will be merged into the * existing scores for the experiment event */ - @NoAutoDetect class Scores @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Scores = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -518,6 +550,34 @@ private constructor( fun build(): Scores = Scores(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Scores = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -629,6 +689,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Source = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackProjectLogsItem.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackProjectLogsItem.kt index 3741b996..a121b9e5 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackProjectLogsItem.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackProjectLogsItem.kt @@ -7,44 +7,42 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 -@NoAutoDetect class FeedbackProjectLogsItem -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("comment") - @ExcludeMissing - private val comment: JsonField = JsonMissing.of(), - @JsonProperty("expected") @ExcludeMissing private val expected: JsonValue = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("scores") - @ExcludeMissing - private val scores: JsonField = JsonMissing.of(), - @JsonProperty("source") - @ExcludeMissing - private val source: JsonField = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val comment: JsonField, + private val expected: JsonValue, + private val metadata: JsonField, + private val scores: JsonField, + private val source: JsonField, + private val tags: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("comment") @ExcludeMissing comment: JsonField = JsonMissing.of(), + @JsonProperty("expected") @ExcludeMissing expected: JsonValue = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("scores") @ExcludeMissing scores: JsonField = JsonMissing.of(), + @JsonProperty("source") @ExcludeMissing source: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this(id, comment, expected, metadata, scores, source, tags, mutableMapOf()) + /** * The id of the project logs event to log feedback for. This is the row `id` returned by `POST * /v1/project_logs/{project_id}/insert` @@ -60,7 +58,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun comment(): Optional = Optional.ofNullable(comment.getNullable("comment")) + fun comment(): Optional = comment.getOptional("comment") /** * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to @@ -76,7 +74,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** * A dictionary of numeric values (between 0 and 1) to log. These scores will be merged into the @@ -85,7 +83,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun scores(): Optional = Optional.ofNullable(scores.getNullable("scores")) + fun scores(): Optional = scores.getOptional("scores") /** * The source of the feedback. Must be one of "external" (default), "app", or "api" @@ -93,7 +91,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun source(): Optional = Optional.ofNullable(source.getNullable("source")) + fun source(): Optional = source.getOptional("source") /** * A list of tags to log @@ -101,7 +99,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [id]. @@ -145,25 +143,15 @@ private constructor( */ @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): FeedbackProjectLogsItem = apply { - if (validated) { - return@apply - } - - id() - comment() - metadata().ifPresent { it.validate() } - scores().ifPresent { it.validate() } - source() - tags() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -354,37 +342,64 @@ private constructor( scores, source, (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): FeedbackProjectLogsItem = apply { + if (validated) { + return@apply + } + + id() + comment() + metadata().ifPresent { it.validate() } + scores().ifPresent { it.validate() } + source().ifPresent { it.validate() } + tags() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (comment.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (scores.asKnown().getOrNull()?.validity() ?: 0) + + (source.asKnown().getOrNull()?.validity() ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + /** * A dictionary with additional data about the feedback. If you have a `user_id`, you can log it * here and access it in the Braintrust UI. Note, this metadata does not correspond to the main * event itself, but rather the audit log attached to the event. */ - @NoAutoDetect class Metadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -430,6 +445,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -451,28 +494,17 @@ private constructor( * A dictionary of numeric values (between 0 and 1) to log. These scores will be merged into the * existing scores for the project logs event */ - @NoAutoDetect class Scores @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Scores = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -518,6 +550,34 @@ private constructor( fun build(): Scores = Scores(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Scores = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -629,6 +689,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Source = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackResponseSchema.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackResponseSchema.kt index 8bbcb0f7..ef0b762b 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackResponseSchema.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackResponseSchema.kt @@ -7,27 +7,27 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 kotlin.jvm.optionals.getOrNull -@NoAutoDetect class FeedbackResponseSchema -@JsonCreator private constructor( - @JsonProperty("status") - @ExcludeMissing - private val status: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val status: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of() + ) : this(status, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected value). @@ -41,20 +41,15 @@ private constructor( */ @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): FeedbackResponseSchema = apply { - if (validated) { - return@apply - } - - status() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -127,10 +122,36 @@ private constructor( fun build(): FeedbackResponseSchema = FeedbackResponseSchema( checkRequired("status", status), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): FeedbackResponseSchema = apply { + if (validated) { + return@apply + } + + status().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (status.asKnown().getOrNull()?.validity() ?: 0) + class Status @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -212,6 +233,33 @@ private constructor( BraintrustInvalidDataException("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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FetchDatasetEventsResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FetchDatasetEventsResponse.kt index 627d9ef7..e6658cf9 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FetchDatasetEventsResponse.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FetchDatasetEventsResponse.kt @@ -6,33 +6,34 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 -@NoAutoDetect class FetchDatasetEventsResponse -@JsonCreator private constructor( - @JsonProperty("events") - @ExcludeMissing - private val events: JsonField> = JsonMissing.of(), - @JsonProperty("cursor") - @ExcludeMissing - private val cursor: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val events: JsonField>, + private val cursor: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("events") + @ExcludeMissing + events: JsonField> = JsonMissing.of(), + @JsonProperty("cursor") @ExcludeMissing cursor: JsonField = JsonMissing.of(), + ) : this(events, cursor, mutableMapOf()) + /** * A list of fetched events * @@ -50,7 +51,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun cursor(): Optional = Optional.ofNullable(cursor.getNullable("cursor")) + fun cursor(): Optional = cursor.getOptional("cursor") /** * Returns the raw JSON value of [events]. @@ -66,21 +67,15 @@ private constructor( */ @JsonProperty("cursor") @ExcludeMissing fun _cursor(): JsonField = cursor + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): FetchDatasetEventsResponse = apply { - if (validated) { - return@apply - } - - events().forEach { it.validate() } - cursor() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -191,10 +186,40 @@ private constructor( FetchDatasetEventsResponse( checkRequired("events", events).map { it.toImmutable() }, cursor, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): FetchDatasetEventsResponse = apply { + if (validated) { + return@apply + } + + events().forEach { it.validate() } + cursor() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (events.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (cursor.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FetchExperimentEventsResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FetchExperimentEventsResponse.kt index 585ff788..12ee5436 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FetchExperimentEventsResponse.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FetchExperimentEventsResponse.kt @@ -6,33 +6,34 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 -@NoAutoDetect class FetchExperimentEventsResponse -@JsonCreator private constructor( - @JsonProperty("events") - @ExcludeMissing - private val events: JsonField> = JsonMissing.of(), - @JsonProperty("cursor") - @ExcludeMissing - private val cursor: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val events: JsonField>, + private val cursor: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("events") + @ExcludeMissing + events: JsonField> = JsonMissing.of(), + @JsonProperty("cursor") @ExcludeMissing cursor: JsonField = JsonMissing.of(), + ) : this(events, cursor, mutableMapOf()) + /** * A list of fetched events * @@ -50,7 +51,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun cursor(): Optional = Optional.ofNullable(cursor.getNullable("cursor")) + fun cursor(): Optional = cursor.getOptional("cursor") /** * Returns the raw JSON value of [events]. @@ -66,21 +67,15 @@ private constructor( */ @JsonProperty("cursor") @ExcludeMissing fun _cursor(): JsonField = cursor + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): FetchExperimentEventsResponse = apply { - if (validated) { - return@apply - } - - events().forEach { it.validate() } - cursor() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -192,10 +187,40 @@ private constructor( FetchExperimentEventsResponse( checkRequired("events", events).map { it.toImmutable() }, cursor, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): FetchExperimentEventsResponse = apply { + if (validated) { + return@apply + } + + events().forEach { it.validate() } + cursor() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (events.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (cursor.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FetchProjectLogsEventsResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FetchProjectLogsEventsResponse.kt index 81de5770..ad177f9c 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FetchProjectLogsEventsResponse.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FetchProjectLogsEventsResponse.kt @@ -6,33 +6,34 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 -@NoAutoDetect class FetchProjectLogsEventsResponse -@JsonCreator private constructor( - @JsonProperty("events") - @ExcludeMissing - private val events: JsonField> = JsonMissing.of(), - @JsonProperty("cursor") - @ExcludeMissing - private val cursor: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val events: JsonField>, + private val cursor: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("events") + @ExcludeMissing + events: JsonField> = JsonMissing.of(), + @JsonProperty("cursor") @ExcludeMissing cursor: JsonField = JsonMissing.of(), + ) : this(events, cursor, mutableMapOf()) + /** * A list of fetched events * @@ -50,7 +51,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun cursor(): Optional = Optional.ofNullable(cursor.getNullable("cursor")) + fun cursor(): Optional = cursor.getOptional("cursor") /** * Returns the raw JSON value of [events]. @@ -68,21 +69,15 @@ private constructor( */ @JsonProperty("cursor") @ExcludeMissing fun _cursor(): JsonField = cursor + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): FetchProjectLogsEventsResponse = apply { - if (validated) { - return@apply - } - - events().forEach { it.validate() } - cursor() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -195,10 +190,40 @@ private constructor( FetchProjectLogsEventsResponse( checkRequired("events", events).map { it.toImmutable() }, cursor, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): FetchProjectLogsEventsResponse = apply { + if (validated) { + return@apply + } + + events().forEach { it.validate() } + cursor() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (events.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (cursor.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Function.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Function.kt index 9811c9a5..d3a0bb30 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Function.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Function.kt @@ -9,11 +9,10 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect +import com.braintrustdata.api.core.allMaxBy import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -28,55 +27,82 @@ 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 -@NoAutoDetect class Function -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("_xact_id") - @ExcludeMissing - private val _xactId: JsonField = JsonMissing.of(), - @JsonProperty("function_data") - @ExcludeMissing - private val functionData: JsonField = JsonMissing.of(), - @JsonProperty("log_id") @ExcludeMissing private val logId: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("org_id") @ExcludeMissing private val orgId: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("slug") @ExcludeMissing private val slug: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("function_schema") - @ExcludeMissing - private val functionSchema: JsonField = JsonMissing.of(), - @JsonProperty("function_type") - @ExcludeMissing - private val functionType: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("origin") - @ExcludeMissing - private val origin: JsonField = JsonMissing.of(), - @JsonProperty("prompt_data") - @ExcludeMissing - private val promptData: JsonField = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val _xactId: JsonField, + private val functionData: JsonField, + private val logId: JsonField, + private val name: JsonField, + private val orgId: JsonField, + private val projectId: JsonField, + private val slug: JsonField, + private val created: JsonField, + private val description: JsonField, + private val functionSchema: JsonField, + private val functionType: JsonField, + private val metadata: JsonField, + private val origin: JsonField, + private val promptData: JsonField, + private val tags: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("_xact_id") @ExcludeMissing _xactId: JsonField = JsonMissing.of(), + @JsonProperty("function_data") + @ExcludeMissing + functionData: JsonField = JsonMissing.of(), + @JsonProperty("log_id") @ExcludeMissing logId: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("org_id") @ExcludeMissing orgId: JsonField = JsonMissing.of(), + @JsonProperty("project_id") @ExcludeMissing projectId: JsonField = JsonMissing.of(), + @JsonProperty("slug") @ExcludeMissing slug: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("function_schema") + @ExcludeMissing + functionSchema: JsonField = JsonMissing.of(), + @JsonProperty("function_type") + @ExcludeMissing + functionType: JsonField = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("origin") @ExcludeMissing origin: JsonField = JsonMissing.of(), + @JsonProperty("prompt_data") + @ExcludeMissing + promptData: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this( + id, + _xactId, + functionData, + logId, + name, + orgId, + projectId, + slug, + created, + description, + functionSchema, + functionType, + metadata, + origin, + promptData, + tags, + mutableMapOf(), + ) + /** * Unique identifier for the prompt * @@ -147,7 +173,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Textual description of the prompt @@ -155,8 +181,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun description(): Optional = description.getOptional("description") /** * JSON schema for the function's parameters and return type @@ -164,15 +189,13 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun functionSchema(): Optional = - Optional.ofNullable(functionSchema.getNullable("function_schema")) + fun functionSchema(): Optional = functionSchema.getOptional("function_schema") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun functionType(): Optional = - Optional.ofNullable(functionType.getNullable("function_type")) + fun functionType(): Optional = functionType.getOptional("function_type") /** * User-controlled metadata about the prompt @@ -180,13 +203,13 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun origin(): Optional = Optional.ofNullable(origin.getNullable("origin")) + fun origin(): Optional = origin.getOptional("origin") /** * The prompt, model, and its parameters @@ -194,8 +217,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun promptData(): Optional = - Optional.ofNullable(promptData.getNullable("prompt_data")) + fun promptData(): Optional = promptData.getOptional("prompt_data") /** * A list of tags for the prompt @@ -203,7 +225,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [id]. @@ -325,35 +347,15 @@ private constructor( */ @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Function = apply { - if (validated) { - return@apply - } - - id() - _xactId() - functionData().validate() - logId() - name() - orgId() - projectId() - slug() - created() - description() - functionSchema().ifPresent { it.validate() } - functionType() - metadata().ifPresent { it.validate() } - origin().ifPresent { it.validate() } - promptData().ifPresent { it.validate() } - tags() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -715,10 +717,68 @@ private constructor( origin, promptData, (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Function = apply { + if (validated) { + return@apply + } + + id() + _xactId() + functionData().validate() + logId().validate() + name() + orgId() + projectId() + slug() + created() + description() + functionSchema().ifPresent { it.validate() } + functionType().ifPresent { it.validate() } + metadata().ifPresent { it.validate() } + origin().ifPresent { it.validate() } + promptData().ifPresent { it.validate() } + tags() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (_xactId.asKnown().isPresent) 1 else 0) + + (functionData.asKnown().getOrNull()?.validity() ?: 0) + + (logId.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (orgId.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (slug.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (functionSchema.asKnown().getOrNull()?.validity() ?: 0) + + (functionType.asKnown().getOrNull()?.validity() ?: 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (origin.asKnown().getOrNull()?.validity() ?: 0) + + (promptData.asKnown().getOrNull()?.validity() ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + @JsonDeserialize(using = FunctionData.Deserializer::class) @JsonSerialize(using = FunctionData.Serializer::class) class FunctionData @@ -749,14 +809,13 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { prompt != null -> visitor.visitPrompt(prompt) code != null -> visitor.visitCode(code) global != null -> visitor.visitGlobal(global) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -783,6 +842,34 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitPrompt(prompt: Prompt) = prompt.validity() + + override fun visitCode(code: Code) = code.validity() + + override fun visitGlobal(global: Global) = global.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -843,20 +930,31 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): FunctionData { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return FunctionData(prompt = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return FunctionData(code = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return FunctionData(global = it, _json = json) - } - - return FunctionData(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionData(prompt = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionData(code = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionData(global = 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 -> FunctionData(_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() + } } } @@ -877,17 +975,17 @@ private constructor( } } - @NoAutoDetect class Prompt - @JsonCreator private constructor( - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of() + ) : this(type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -902,20 +1000,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Prompt = apply { - if (validated) { - return@apply - } - - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -990,9 +1083,37 @@ private constructor( * @throws IllegalStateException if any required field is unset. */ fun build(): Prompt = - Prompt(checkRequired("type", type), additionalProperties.toImmutable()) + Prompt(checkRequired("type", type), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Prompt = apply { + if (validated) { + return@apply + } + + type().validate() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1077,6 +1198,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -1108,20 +1256,19 @@ private constructor( "Prompt{type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Code - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -1150,21 +1297,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Code = apply { - if (validated) { - return@apply - } - - data().validate() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1263,10 +1404,41 @@ private constructor( Code( checkRequired("data", data), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Code = apply { + if (validated) { + return@apply + } + + data().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (data.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + @JsonDeserialize(using = Data.Deserializer::class) @JsonSerialize(using = Data.Serializer::class) class Data @@ -1290,13 +1462,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { bundle != null -> visitor.visitBundle(bundle) inline != null -> visitor.visitInline(inline) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1319,6 +1490,32 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitBundle(bundle: Bundle) = bundle.validity() + + override fun visitInline(inline: Inline) = inline.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1374,16 +1571,29 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Data { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Data(bundle = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Data(inline = it, _json = json) - } - - return Data(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Data(bundle = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Data(inline = 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 -> Data(_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() + } } } @@ -1403,30 +1613,43 @@ private constructor( } } - @NoAutoDetect class Bundle - @JsonCreator private constructor( - @JsonProperty("bundle_id") - @ExcludeMissing - private val bundleId: JsonField = JsonMissing.of(), - @JsonProperty("location") - @ExcludeMissing - private val location: JsonField = JsonMissing.of(), - @JsonProperty("runtime_context") - @ExcludeMissing - private val runtimeContext: JsonField = - JsonMissing.of(), - @JsonProperty("preview") - @ExcludeMissing - private val preview: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val bundleId: JsonField, + private val location: JsonField, + private val runtimeContext: JsonField, + private val preview: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("bundle_id") + @ExcludeMissing + bundleId: JsonField = JsonMissing.of(), + @JsonProperty("location") + @ExcludeMissing + location: JsonField = JsonMissing.of(), + @JsonProperty("runtime_context") + @ExcludeMissing + runtimeContext: JsonField = JsonMissing.of(), + @JsonProperty("preview") + @ExcludeMissing + preview: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(bundleId, location, runtimeContext, preview, type, mutableMapOf()) + + fun toCodeBundle(): CodeBundle = + CodeBundle.builder() + .bundleId(bundleId) + .location(location) + .runtimeContext(runtimeContext) + .preview(preview) + .build() + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -1455,8 +1678,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ - fun preview(): Optional = - Optional.ofNullable(preview.getNullable("preview")) + fun preview(): Optional = preview.getOptional("preview") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected @@ -1513,36 +1735,19 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toCodeBundle(): CodeBundle = - CodeBundle.builder() - .bundleId(bundleId) - .location(location) - .runtimeContext(runtimeContext) - .preview(preview) - .build() + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - private var validated: Boolean = false + fun toBuilder() = Builder().from(this) - fun validate(): Bundle = apply { - if (validated) { - return@apply - } - - bundleId() - location().validate() - runtimeContext().validate() - preview() - type() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { + companion object { /** * Returns a mutable builder for constructing an instance of [Bundle]. @@ -1705,10 +1910,47 @@ private constructor( checkRequired("runtimeContext", runtimeContext), preview, checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Bundle = apply { + if (validated) { + return@apply + } + + bundleId() + location().validate() + runtimeContext().validate() + preview() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (bundleId.asKnown().isPresent) 1 else 0) + + (location.asKnown().getOrNull()?.validity() ?: 0) + + (runtimeContext.asKnown().getOrNull()?.validity() ?: 0) + + (if (preview.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1797,6 +2039,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -1828,23 +2098,27 @@ private constructor( "Bundle{bundleId=$bundleId, location=$location, runtimeContext=$runtimeContext, preview=$preview, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Inline - @JsonCreator private constructor( - @JsonProperty("code") - @ExcludeMissing - private val code: JsonField = JsonMissing.of(), - @JsonProperty("runtime_context") - @ExcludeMissing - private val runtimeContext: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val code: JsonField, + private val runtimeContext: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("code") + @ExcludeMissing + code: JsonField = JsonMissing.of(), + @JsonProperty("runtime_context") + @ExcludeMissing + runtimeContext: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(code, runtimeContext, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -1893,22 +2167,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Inline = apply { - if (validated) { - return@apply - } - - code() - runtimeContext().validate() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2021,25 +2288,60 @@ private constructor( checkRequired("code", code), checkRequired("runtimeContext", runtimeContext), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Inline = apply { + if (validated) { + return@apply + } + + code() + runtimeContext().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (code.asKnown().isPresent) 1 else 0) + + (runtimeContext.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class RuntimeContext - @JsonCreator private constructor( - @JsonProperty("runtime") - @ExcludeMissing - private val runtime: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val runtime: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("runtime") + @ExcludeMissing + runtime: JsonField = JsonMissing.of(), + @JsonProperty("version") + @ExcludeMissing + version: JsonField = JsonMissing.of(), + ) : this(runtime, version, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an * unexpected type or is unexpectedly missing or null (e.g. if the server @@ -2074,21 +2376,15 @@ private constructor( @ExcludeMissing fun _version(): JsonField = version + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): RuntimeContext = apply { - if (validated) { - return@apply - } - - runtime() - version() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2189,10 +2485,41 @@ private constructor( RuntimeContext( checkRequired("runtime", runtime), checkRequired("version", version), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): RuntimeContext = apply { + if (validated) { + return@apply + } + + runtime().validate() + version() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (runtime.asKnown().getOrNull()?.validity() ?: 0) + + (if (version.asKnown().isPresent) 1 else 0) + class Runtime @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -2292,6 +2619,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Runtime = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2411,6 +2766,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2527,6 +2910,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2558,20 +2968,19 @@ private constructor( "Code{data=$data, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Global - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(name, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -2600,21 +3009,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Global = apply { - if (validated) { - return@apply - } - - name() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2707,10 +3110,41 @@ private constructor( Global( checkRequired("name", name), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Global = apply { + if (validated) { + return@apply + } + + name() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -2795,6 +3229,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2909,6 +3370,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): LogId = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2923,35 +3411,32 @@ private constructor( } /** JSON schema for the function's parameters and return type */ - @NoAutoDetect class FunctionSchema - @JsonCreator private constructor( - @JsonProperty("parameters") - @ExcludeMissing - private val parameters: JsonValue = JsonMissing.of(), - @JsonProperty("returns") @ExcludeMissing private val returns: JsonValue = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val parameters: JsonValue, + private val returns: JsonValue, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("parameters") @ExcludeMissing parameters: JsonValue = JsonMissing.of(), + @JsonProperty("returns") @ExcludeMissing returns: JsonValue = JsonMissing.of(), + ) : this(parameters, returns, mutableMapOf()) + @JsonProperty("parameters") @ExcludeMissing fun _parameters(): JsonValue = parameters @JsonProperty("returns") @ExcludeMissing fun _returns(): JsonValue = returns + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): FunctionSchema = apply { - if (validated) { - return@apply - } - - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3004,9 +3489,35 @@ private constructor( * Further updates to this [Builder] will not mutate the returned instance. */ fun build(): FunctionSchema = - FunctionSchema(parameters, returns, additionalProperties.toImmutable()) + FunctionSchema(parameters, returns, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): FunctionSchema = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = 0 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3127,6 +3638,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): FunctionType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -3141,28 +3679,17 @@ private constructor( } /** User-controlled metadata about the prompt */ - @NoAutoDetect class Metadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -3208,6 +3735,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -3225,23 +3780,27 @@ private constructor( override fun toString() = "Metadata{additionalProperties=$additionalProperties}" } - @NoAutoDetect class Origin - @JsonCreator private constructor( - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("internal") - @ExcludeMissing - private val internal_: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val objectId: JsonField, + private val objectType: JsonField, + private val internal_: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("object_id") + @ExcludeMissing + objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("internal") + @ExcludeMissing + internal_: JsonField = JsonMissing.of(), + ) : this(objectId, objectType, internal_, mutableMapOf()) + /** * Id of the object the function is originating from * @@ -3265,7 +3824,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun internal_(): Optional = Optional.ofNullable(internal_.getNullable("internal")) + fun internal_(): Optional = internal_.getOptional("internal") /** * Returns the raw JSON value of [objectId]. @@ -3290,22 +3849,15 @@ private constructor( */ @JsonProperty("internal") @ExcludeMissing fun _internal_(): JsonField = internal_ + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Origin = apply { - if (validated) { - return@apply - } - - objectId() - objectType() - internal_() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3427,10 +3979,43 @@ private constructor( checkRequired("objectId", objectId), checkRequired("objectType", objectType), internal_, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Origin = apply { + if (validated) { + return@apply + } + + objectId() + objectType().validate() + internal_() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (internal_.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionCreateParams.kt index f902f77a..0e55e810 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionCreateParams.kt @@ -9,14 +9,13 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.allMaxBy import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.braintrustdata.api.models.CodeBundle.* @@ -31,6 +30,7 @@ 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.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -196,529 +196,331 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("function_data") - @ExcludeMissing - private val functionData: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("slug") - @ExcludeMissing - private val slug: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("function_schema") - @ExcludeMissing - private val functionSchema: JsonField = JsonMissing.of(), - @JsonProperty("function_type") - @ExcludeMissing - private val functionType: JsonField = JsonMissing.of(), - @JsonProperty("origin") - @ExcludeMissing - private val origin: JsonField = JsonMissing.of(), - @JsonProperty("prompt_data") - @ExcludeMissing - private val promptData: JsonField = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + fun toBuilder() = Builder().from(this) - /** - * @throws BraintrustInvalidDataException 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 functionData(): FunctionData = functionData.getRequired("function_data") + companion object { /** - * Name of the prompt + * Returns a mutable builder for constructing an instance of [FunctionCreateParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .functionData() + * .name() + * .projectId() + * .slug() + * ``` */ - fun name(): String = name.getRequired("name") + @JvmStatic fun builder() = Builder() + } - /** - * Unique identifier for the project that the prompt belongs under - * - * @throws BraintrustInvalidDataException 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 projectId(): String = projectId.getRequired("project_id") + /** A builder for [FunctionCreateParams]. */ + class Builder internal constructor() { - /** - * Unique identifier for the prompt - * - * @throws BraintrustInvalidDataException 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 slug(): String = slug.getRequired("slug") + 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(functionCreateParams: FunctionCreateParams) = apply { + body = functionCreateParams.body.toBuilder() + additionalHeaders = functionCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = functionCreateParams.additionalQueryParams.toBuilder() + } /** - * Textual description of the prompt + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [functionData] + * - [name] + * - [projectId] + * - [slug] + * - [description] + * - etc. */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun body(body: Body) = apply { this.body = body.toBuilder() } + + fun functionData(functionData: FunctionData) = apply { body.functionData(functionData) } /** - * JSON schema for the function's parameters and return type + * Sets [Builder.functionData] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.functionData] with a well-typed [FunctionData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun functionSchema(): Optional = - Optional.ofNullable(functionSchema.getNullable("function_schema")) + fun functionData(functionData: JsonField) = apply { + body.functionData(functionData) + } - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun functionType(): Optional = - Optional.ofNullable(functionType.getNullable("function_type")) + /** Alias for calling [functionData] with `FunctionData.ofPrompt(prompt)`. */ + fun functionData(prompt: FunctionData.Prompt) = apply { body.functionData(prompt) } - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun origin(): Optional = Optional.ofNullable(origin.getNullable("origin")) + /** Alias for calling [functionData] with `FunctionData.ofCode(code)`. */ + fun functionData(code: FunctionData.Code) = apply { body.functionData(code) } - /** - * The prompt, model, and its parameters - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun promptData(): Optional = - Optional.ofNullable(promptData.getNullable("prompt_data")) + /** Alias for calling [functionData] with `FunctionData.ofGlobal(global)`. */ + fun functionData(global: FunctionData.Global) = apply { body.functionData(global) } - /** - * A list of tags for the prompt - * - * @throws BraintrustInvalidDataException 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")) + /** Name of the prompt */ + fun name(name: String) = apply { body.name(name) } /** - * Returns the raw JSON value of [functionData]. + * Sets [Builder.name] to an arbitrary JSON value. * - * Unlike [functionData], this method doesn't throw if the JSON field has an unexpected - * type. + * 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. */ - @JsonProperty("function_data") - @ExcludeMissing - fun _functionData(): JsonField = functionData + fun name(name: JsonField) = apply { body.name(name) } + + /** Unique identifier for the project that the prompt belongs under */ + fun projectId(projectId: String) = apply { body.projectId(projectId) } /** - * Returns the raw JSON value of [name]. + * Sets [Builder.projectId] to an arbitrary JSON value. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } + + /** Unique identifier for the prompt */ + fun slug(slug: String) = apply { body.slug(slug) } /** - * Returns the raw JSON value of [projectId]. + * Sets [Builder.slug] to an arbitrary JSON value. * - * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.slug] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId + fun slug(slug: JsonField) = apply { body.slug(slug) } + + /** Textual description of the prompt */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) /** - * Returns the raw JSON value of [slug]. + * Sets [Builder.description] to an arbitrary JSON value. * - * Unlike [slug], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("slug") @ExcludeMissing fun _slug(): JsonField = slug + fun description(description: JsonField) = apply { body.description(description) } + + /** JSON schema for the function's parameters and return type */ + fun functionSchema(functionSchema: FunctionSchema?) = apply { + body.functionSchema(functionSchema) + } + + /** Alias for calling [Builder.functionSchema] with `functionSchema.orElse(null)`. */ + fun functionSchema(functionSchema: Optional) = + functionSchema(functionSchema.getOrNull()) /** - * Returns the raw JSON value of [description]. + * Sets [Builder.functionSchema] to an arbitrary JSON value. * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.functionSchema] with a well-typed [FunctionSchema] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description + fun functionSchema(functionSchema: JsonField) = apply { + body.functionSchema(functionSchema) + } + + fun functionType(functionType: FunctionType?) = apply { body.functionType(functionType) } + + /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ + fun functionType(functionType: Optional) = + functionType(functionType.getOrNull()) /** - * Returns the raw JSON value of [functionSchema]. + * Sets [Builder.functionType] to an arbitrary JSON value. * - * Unlike [functionSchema], this method doesn't throw if the JSON field has an unexpected - * type. + * You should usually call [Builder.functionType] with a well-typed [FunctionType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("function_schema") - @ExcludeMissing - fun _functionSchema(): JsonField = functionSchema + fun functionType(functionType: JsonField) = apply { + body.functionType(functionType) + } + + fun origin(origin: Origin?) = apply { body.origin(origin) } + + /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ + fun origin(origin: Optional) = origin(origin.getOrNull()) /** - * Returns the raw JSON value of [functionType]. + * Sets [Builder.origin] to an arbitrary JSON value. * - * Unlike [functionType], this method doesn't throw if the JSON field has an unexpected - * type. + * You should usually call [Builder.origin] with a well-typed [Origin] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("function_type") - @ExcludeMissing - fun _functionType(): JsonField = functionType + fun origin(origin: JsonField) = apply { body.origin(origin) } + + /** The prompt, model, and its parameters */ + fun promptData(promptData: PromptData?) = apply { body.promptData(promptData) } + + /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ + fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) /** - * Returns the raw JSON value of [origin]. + * Sets [Builder.promptData] to an arbitrary JSON value. * - * Unlike [origin], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.promptData] with a well-typed [PromptData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("origin") @ExcludeMissing fun _origin(): JsonField = origin + fun promptData(promptData: JsonField) = apply { body.promptData(promptData) } + + /** A list of tags for the prompt */ + fun tags(tags: List?) = apply { body.tags(tags) } + + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) /** - * Returns the raw JSON value of [promptData]. + * Sets [Builder.tags] to an arbitrary JSON value. * - * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.tags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("prompt_data") - @ExcludeMissing - fun _promptData(): JsonField = promptData + fun tags(tags: JsonField>) = apply { body.tags(tags) } /** - * Returns the raw JSON value of [tags]. + * Adds a single [String] to [tags]. * - * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + fun addTag(tag: String) = apply { body.addTag(tag) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - functionData().validate() - name() - projectId() - slug() - description() - functionSchema().ifPresent { it.validate() } - functionType() - origin().ifPresent { it.validate() } - promptData().ifPresent { it.validate() } - tags() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .functionData() - * .name() - * .projectId() - * .slug() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) } - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var functionData: JsonField? = null - private var name: JsonField? = null - private var projectId: JsonField? = null - private var slug: JsonField? = null - private var description: JsonField = JsonMissing.of() - private var functionSchema: JsonField = JsonMissing.of() - private var functionType: JsonField = JsonMissing.of() - private var origin: JsonField = JsonMissing.of() - private var promptData: JsonField = JsonMissing.of() - private var tags: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - functionData = body.functionData - name = body.name - projectId = body.projectId - slug = body.slug - description = body.description - functionSchema = body.functionSchema - functionType = body.functionType - origin = body.origin - promptData = body.promptData - tags = body.tags.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } - - fun functionData(functionData: FunctionData) = functionData(JsonField.of(functionData)) - - /** - * Sets [Builder.functionData] to an arbitrary JSON value. - * - * You should usually call [Builder.functionData] with a well-typed [FunctionData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun functionData(functionData: JsonField) = apply { - this.functionData = functionData - } - - /** Alias for calling [functionData] with `FunctionData.ofPrompt(prompt)`. */ - fun functionData(prompt: FunctionData.Prompt) = - functionData(FunctionData.ofPrompt(prompt)) - - /** Alias for calling [functionData] with `FunctionData.ofCode(code)`. */ - fun functionData(code: FunctionData.Code) = functionData(FunctionData.ofCode(code)) - - /** Alias for calling [functionData] with `FunctionData.ofGlobal(global)`. */ - fun functionData(global: FunctionData.Global) = - functionData(FunctionData.ofGlobal(global)) - - /** Name of the prompt */ - 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 } - - /** Unique identifier for the project that the prompt belongs under */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - - /** - * Sets [Builder.projectId] to an arbitrary JSON value. - * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } - - /** Unique identifier for the prompt */ - fun slug(slug: String) = slug(JsonField.of(slug)) - - /** - * Sets [Builder.slug] to an arbitrary JSON value. - * - * You should usually call [Builder.slug] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun slug(slug: JsonField) = apply { this.slug = slug } - - /** Textual description of the prompt */ - fun description(description: String?) = description(JsonField.ofNullable(description)) - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } - - /** JSON schema for the function's parameters and return type */ - fun functionSchema(functionSchema: FunctionSchema?) = - functionSchema(JsonField.ofNullable(functionSchema)) - - /** Alias for calling [Builder.functionSchema] with `functionSchema.orElse(null)`. */ - fun functionSchema(functionSchema: Optional) = - functionSchema(functionSchema.getOrNull()) - - /** - * Sets [Builder.functionSchema] to an arbitrary JSON value. - * - * You should usually call [Builder.functionSchema] with a well-typed [FunctionSchema] - * value instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun functionSchema(functionSchema: JsonField) = apply { - this.functionSchema = functionSchema + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - fun functionType(functionType: FunctionType?) = - functionType(JsonField.ofNullable(functionType)) + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ - fun functionType(functionType: Optional) = - functionType(functionType.getOrNull()) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** - * Sets [Builder.functionType] to an arbitrary JSON value. - * - * You should usually call [Builder.functionType] with a well-typed [FunctionType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun functionType(functionType: JsonField) = apply { - this.functionType = functionType - } + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - fun origin(origin: Origin?) = origin(JsonField.ofNullable(origin)) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ - fun origin(origin: Optional) = origin(origin.getOrNull()) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** - * Sets [Builder.origin] to an arbitrary JSON value. - * - * You should usually call [Builder.origin] with a well-typed [Origin] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun origin(origin: JsonField) = apply { this.origin = origin } + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** The prompt, model, and its parameters */ - fun promptData(promptData: PromptData?) = promptData(JsonField.ofNullable(promptData)) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ - fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** - * Sets [Builder.promptData] to an arbitrary JSON value. - * - * You should usually call [Builder.promptData] with a well-typed [PromptData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun promptData(promptData: JsonField) = apply { - this.promptData = promptData - } + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** A list of tags for the prompt */ - fun tags(tags: List?) = tags(JsonField.ofNullable(tags)) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ - fun tags(tags: Optional>) = tags(tags.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.tags] to an arbitrary JSON value. - * - * You should usually call [Builder.tags] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun tags(tags: JsonField>) = apply { - this.tags = tags.map { it.toMutableList() } - } + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Adds a single [String] to [tags]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addTag(tag: String) = apply { - tags = - (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } - } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .functionData() - * .name() - * .projectId() - * .slug() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("functionData", functionData), - checkRequired("name", name), - checkRequired("projectId", projectId), - checkRequired("slug", slug), - description, - functionSchema, - functionType, - origin, - promptData, - (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && functionData == other.functionData && name == other.name && projectId == other.projectId && slug == other.slug && description == other.description && functionSchema == other.functionSchema && functionType == other.functionType && origin == other.origin && promptData == other.promptData && tags == other.tags && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(functionData, name, projectId, slug, description, functionSchema, functionType, origin, promptData, tags, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{functionData=$functionData, name=$name, projectId=$projectId, slug=$slug, description=$description, functionSchema=$functionSchema, functionType=$functionType, origin=$origin, promptData=$promptData, tags=$tags, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [FunctionCreateParams]. + * Returns an immutable instance of [FunctionCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java @@ -727,321 +529,577 @@ private constructor( * .projectId() * .slug() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): FunctionCreateParams = + FunctionCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [FunctionCreateParams]. */ - @NoAutoDetect - class Builder internal constructor() { + fun _body(): Body = body - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + override fun _headers(): Headers = additionalHeaders - @JvmSynthetic - internal fun from(functionCreateParams: FunctionCreateParams) = apply { - body = functionCreateParams.body.toBuilder() - additionalHeaders = functionCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = functionCreateParams.additionalQueryParams.toBuilder() - } + override fun _queryParams(): QueryParams = additionalQueryParams - fun functionData(functionData: FunctionData) = apply { body.functionData(functionData) } + class Body + private constructor( + private val functionData: JsonField, + private val name: JsonField, + private val projectId: JsonField, + private val slug: JsonField, + private val description: JsonField, + private val functionSchema: JsonField, + private val functionType: JsonField, + private val origin: JsonField, + private val promptData: JsonField, + private val tags: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("function_data") + @ExcludeMissing + functionData: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") + @ExcludeMissing + projectId: JsonField = JsonMissing.of(), + @JsonProperty("slug") @ExcludeMissing slug: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("function_schema") + @ExcludeMissing + functionSchema: JsonField = JsonMissing.of(), + @JsonProperty("function_type") + @ExcludeMissing + functionType: JsonField = JsonMissing.of(), + @JsonProperty("origin") @ExcludeMissing origin: JsonField = JsonMissing.of(), + @JsonProperty("prompt_data") + @ExcludeMissing + promptData: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this( + functionData, + name, + projectId, + slug, + description, + functionSchema, + functionType, + origin, + promptData, + tags, + mutableMapOf(), + ) /** - * Sets [Builder.functionData] to an arbitrary JSON value. + * @throws BraintrustInvalidDataException 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 functionData(): FunctionData = functionData.getRequired("function_data") + + /** + * Name of the prompt * - * You should usually call [Builder.functionData] with a well-typed [FunctionData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException 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 functionData(functionData: JsonField) = apply { - body.functionData(functionData) - } + fun name(): String = name.getRequired("name") - /** Alias for calling [functionData] with `FunctionData.ofPrompt(prompt)`. */ - fun functionData(prompt: FunctionData.Prompt) = apply { body.functionData(prompt) } + /** + * Unique identifier for the project that the prompt belongs under + * + * @throws BraintrustInvalidDataException 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 projectId(): String = projectId.getRequired("project_id") - /** Alias for calling [functionData] with `FunctionData.ofCode(code)`. */ - fun functionData(code: FunctionData.Code) = apply { body.functionData(code) } + /** + * Unique identifier for the prompt + * + * @throws BraintrustInvalidDataException 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 slug(): String = slug.getRequired("slug") - /** Alias for calling [functionData] with `FunctionData.ofGlobal(global)`. */ - fun functionData(global: FunctionData.Global) = apply { body.functionData(global) } + /** + * Textual description of the prompt + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") - /** Name of the prompt */ - fun name(name: String) = apply { body.name(name) } + /** + * JSON schema for the function's parameters and return type + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun functionSchema(): Optional = + functionSchema.getOptional("function_schema") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun functionType(): Optional = functionType.getOptional("function_type") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun origin(): Optional = origin.getOptional("origin") + + /** + * The prompt, model, and its parameters + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun promptData(): Optional = promptData.getOptional("prompt_data") /** - * Sets [Builder.name] to an arbitrary JSON value. + * A list of tags for the prompt * - * 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. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun name(name: JsonField) = apply { body.name(name) } - - /** Unique identifier for the project that the prompt belongs under */ - fun projectId(projectId: String) = apply { body.projectId(projectId) } + fun tags(): Optional> = tags.getOptional("tags") /** - * Sets [Builder.projectId] to an arbitrary JSON value. + * Returns the raw JSON value of [functionData]. * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [functionData], this method doesn't throw if the JSON field has an unexpected + * type. */ - fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } - - /** Unique identifier for the prompt */ - fun slug(slug: String) = apply { body.slug(slug) } + @JsonProperty("function_data") + @ExcludeMissing + fun _functionData(): JsonField = functionData /** - * Sets [Builder.slug] to an arbitrary JSON value. + * Returns the raw JSON value of [name]. * - * You should usually call [Builder.slug] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. */ - fun slug(slug: JsonField) = apply { body.slug(slug) } - - /** Textual description of the prompt */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name /** - * Sets [Builder.description] to an arbitrary JSON value. + * Returns the raw JSON value of [projectId]. * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. */ - fun description(description: JsonField) = apply { body.description(description) } - - /** JSON schema for the function's parameters and return type */ - fun functionSchema(functionSchema: FunctionSchema?) = apply { - body.functionSchema(functionSchema) - } - - /** Alias for calling [Builder.functionSchema] with `functionSchema.orElse(null)`. */ - fun functionSchema(functionSchema: Optional) = - functionSchema(functionSchema.getOrNull()) + @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId /** - * Sets [Builder.functionSchema] to an arbitrary JSON value. + * Returns the raw JSON value of [slug]. * - * You should usually call [Builder.functionSchema] with a well-typed [FunctionSchema] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * Unlike [slug], this method doesn't throw if the JSON field has an unexpected type. */ - fun functionSchema(functionSchema: JsonField) = apply { - body.functionSchema(functionSchema) - } - - fun functionType(functionType: FunctionType?) = apply { body.functionType(functionType) } - - /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ - fun functionType(functionType: Optional) = - functionType(functionType.getOrNull()) + @JsonProperty("slug") @ExcludeMissing fun _slug(): JsonField = slug /** - * Sets [Builder.functionType] to an arbitrary JSON value. + * Returns the raw JSON value of [description]. * - * You should usually call [Builder.functionType] with a well-typed [FunctionType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. */ - fun functionType(functionType: JsonField) = apply { - body.functionType(functionType) - } - - fun origin(origin: Origin?) = apply { body.origin(origin) } - - /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ - fun origin(origin: Optional) = origin(origin.getOrNull()) + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description /** - * Sets [Builder.origin] to an arbitrary JSON value. + * Returns the raw JSON value of [functionSchema]. * - * You should usually call [Builder.origin] with a well-typed [Origin] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [functionSchema], this method doesn't throw if the JSON field has an unexpected + * type. */ - fun origin(origin: JsonField) = apply { body.origin(origin) } - - /** The prompt, model, and its parameters */ - fun promptData(promptData: PromptData?) = apply { body.promptData(promptData) } - - /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ - fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) + @JsonProperty("function_schema") + @ExcludeMissing + fun _functionSchema(): JsonField = functionSchema /** - * Sets [Builder.promptData] to an arbitrary JSON value. + * Returns the raw JSON value of [functionType]. * - * You should usually call [Builder.promptData] with a well-typed [PromptData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * Unlike [functionType], this method doesn't throw if the JSON field has an unexpected + * type. */ - fun promptData(promptData: JsonField) = apply { body.promptData(promptData) } - - /** A list of tags for the prompt */ - fun tags(tags: List?) = apply { body.tags(tags) } + @JsonProperty("function_type") + @ExcludeMissing + fun _functionType(): JsonField = functionType - /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ - fun tags(tags: Optional>) = tags(tags.getOrNull()) + /** + * Returns the raw JSON value of [origin]. + * + * Unlike [origin], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("origin") @ExcludeMissing fun _origin(): JsonField = origin /** - * Sets [Builder.tags] to an arbitrary JSON value. + * Returns the raw JSON value of [promptData]. * - * You should usually call [Builder.tags] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. */ - fun tags(tags: JsonField>) = apply { body.tags(tags) } + @JsonProperty("prompt_data") + @ExcludeMissing + fun _promptData(): JsonField = promptData /** - * Adds a single [String] to [tags]. + * Returns the raw JSON value of [tags]. * - * @throws IllegalStateException if the field was previously set to a non-list. + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. */ - fun addTag(tag: String) = apply { body.addTag(tag) } + @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) + @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 + * .functionData() + * .name() + * .projectId() + * .slug() + * ``` + */ + @JvmStatic fun builder() = Builder() } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var functionData: JsonField? = null + private var name: JsonField? = null + private var projectId: JsonField? = null + private var slug: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var functionSchema: JsonField = JsonMissing.of() + private var functionType: JsonField = JsonMissing.of() + private var origin: JsonField = JsonMissing.of() + private var promptData: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + functionData = body.functionData + name = body.name + projectId = body.projectId + slug = body.slug + description = body.description + functionSchema = body.functionSchema + functionType = body.functionType + origin = body.origin + promptData = body.promptData + tags = body.tags.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + fun functionData(functionData: FunctionData) = functionData(JsonField.of(functionData)) + + /** + * Sets [Builder.functionData] to an arbitrary JSON value. + * + * You should usually call [Builder.functionData] with a well-typed [FunctionData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun functionData(functionData: JsonField) = apply { + this.functionData = functionData + } + + /** Alias for calling [functionData] with `FunctionData.ofPrompt(prompt)`. */ + fun functionData(prompt: FunctionData.Prompt) = + functionData(FunctionData.ofPrompt(prompt)) + + /** Alias for calling [functionData] with `FunctionData.ofCode(code)`. */ + fun functionData(code: FunctionData.Code) = functionData(FunctionData.ofCode(code)) + + /** Alias for calling [functionData] with `FunctionData.ofGlobal(global)`. */ + fun functionData(global: FunctionData.Global) = + functionData(FunctionData.ofGlobal(global)) + + /** Name of the prompt */ + 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 } + + /** Unique identifier for the project that the prompt belongs under */ + fun projectId(projectId: String) = projectId(JsonField.of(projectId)) + + /** + * Sets [Builder.projectId] to an arbitrary JSON value. + * + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun projectId(projectId: JsonField) = apply { this.projectId = projectId } + + /** Unique identifier for the prompt */ + fun slug(slug: String) = slug(JsonField.of(slug)) + + /** + * Sets [Builder.slug] to an arbitrary JSON value. + * + * You should usually call [Builder.slug] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun slug(slug: JsonField) = apply { this.slug = slug } + + /** Textual description of the prompt */ + fun description(description: String?) = description(JsonField.ofNullable(description)) - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) - } + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** JSON schema for the function's parameters and return type */ + fun functionSchema(functionSchema: FunctionSchema?) = + functionSchema(JsonField.ofNullable(functionSchema)) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** Alias for calling [Builder.functionSchema] with `functionSchema.orElse(null)`. */ + fun functionSchema(functionSchema: Optional) = + functionSchema(functionSchema.getOrNull()) - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Sets [Builder.functionSchema] to an arbitrary JSON value. + * + * You should usually call [Builder.functionSchema] with a well-typed [FunctionSchema] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun functionSchema(functionSchema: JsonField) = apply { + this.functionSchema = functionSchema + } - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + fun functionType(functionType: FunctionType?) = + functionType(JsonField.ofNullable(functionType)) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ + fun functionType(functionType: Optional) = + functionType(functionType.getOrNull()) - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Sets [Builder.functionType] to an arbitrary JSON value. + * + * You should usually call [Builder.functionType] with a well-typed [FunctionType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun functionType(functionType: JsonField) = apply { + this.functionType = functionType + } - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + fun origin(origin: Origin?) = origin(JsonField.ofNullable(origin)) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ + fun origin(origin: Optional) = origin(origin.getOrNull()) - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** + * Sets [Builder.origin] to an arbitrary JSON value. + * + * You should usually call [Builder.origin] with a well-typed [Origin] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun origin(origin: JsonField) = apply { this.origin = origin } - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** The prompt, model, and its parameters */ + fun promptData(promptData: PromptData?) = promptData(JsonField.ofNullable(promptData)) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ + fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + /** + * Sets [Builder.promptData] to an arbitrary JSON value. + * + * You should usually call [Builder.promptData] with a well-typed [PromptData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun promptData(promptData: JsonField) = apply { + this.promptData = promptData + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + /** A list of tags for the prompt */ + fun tags(tags: List?) = tags(JsonField.ofNullable(tags)) - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** + * Sets [Builder.tags] to an arbitrary JSON value. + * + * You should usually call [Builder.tags] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tags(tags: JsonField>) = apply { + this.tags = tags.map { it.toMutableList() } + } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { + tags = + (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .functionData() + * .name() + * .projectId() + * .slug() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("functionData", functionData), + checkRequired("name", name), + checkRequired("projectId", projectId), + checkRequired("slug", slug), + description, + functionSchema, + functionType, + origin, + promptData, + (tags ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + private var validated: Boolean = false - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + fun validate(): Body = apply { + if (validated) { + return@apply + } - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + functionData().validate() + name() + projectId() + slug() + description() + functionSchema().ifPresent { it.validate() } + functionType().ifPresent { it.validate() } + origin().ifPresent { it.validate() } + promptData().ifPresent { it.validate() } + tags() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + /** - * Returns an immutable instance of [FunctionCreateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .functionData() - * .name() - * .projectId() - * .slug() - * ``` + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * @throws IllegalStateException if any required field is unset. + * Used for best match union deserialization. */ - fun build(): FunctionCreateParams = - FunctionCreateParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + @JvmSynthetic + internal fun validity(): Int = + (functionData.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (slug.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (functionSchema.asKnown().getOrNull()?.validity() ?: 0) + + (functionType.asKnown().getOrNull()?.validity() ?: 0) + + (origin.asKnown().getOrNull()?.validity() ?: 0) + + (promptData.asKnown().getOrNull()?.validity() ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && functionData == other.functionData && name == other.name && projectId == other.projectId && slug == other.slug && description == other.description && functionSchema == other.functionSchema && functionType == other.functionType && origin == other.origin && promptData == other.promptData && tags == other.tags && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(functionData, name, projectId, slug, description, functionSchema, functionType, origin, promptData, tags, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{functionData=$functionData, name=$name, projectId=$projectId, slug=$slug, description=$description, functionSchema=$functionSchema, functionType=$functionType, origin=$origin, promptData=$promptData, tags=$tags, additionalProperties=$additionalProperties}" } @JsonDeserialize(using = FunctionData.Deserializer::class) @@ -1074,14 +1132,13 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { prompt != null -> visitor.visitPrompt(prompt) code != null -> visitor.visitCode(code) global != null -> visitor.visitGlobal(global) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1108,6 +1165,34 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitPrompt(prompt: Prompt) = prompt.validity() + + override fun visitCode(code: Code) = code.validity() + + override fun visitGlobal(global: Global) = global.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1168,20 +1253,31 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): FunctionData { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return FunctionData(prompt = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return FunctionData(code = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return FunctionData(global = it, _json = json) - } - - return FunctionData(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionData(prompt = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionData(code = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionData(global = 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 -> FunctionData(_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() + } } } @@ -1202,17 +1298,17 @@ private constructor( } } - @NoAutoDetect class Prompt - @JsonCreator private constructor( - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of() + ) : this(type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -1227,20 +1323,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Prompt = apply { - if (validated) { - return@apply - } - - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1315,9 +1406,37 @@ private constructor( * @throws IllegalStateException if any required field is unset. */ fun build(): Prompt = - Prompt(checkRequired("type", type), additionalProperties.toImmutable()) + Prompt(checkRequired("type", type), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Prompt = apply { + if (validated) { + return@apply + } + + type().validate() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1402,6 +1521,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -1433,20 +1579,19 @@ private constructor( "Prompt{type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Code - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -1475,21 +1620,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Code = apply { - if (validated) { - return@apply - } - - data().validate() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1588,10 +1727,41 @@ private constructor( Code( checkRequired("data", data), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Code = apply { + if (validated) { + return@apply + } + + data().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (data.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + @JsonDeserialize(using = Data.Deserializer::class) @JsonSerialize(using = Data.Serializer::class) class Data @@ -1615,13 +1785,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { bundle != null -> visitor.visitBundle(bundle) inline != null -> visitor.visitInline(inline) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1644,6 +1813,32 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitBundle(bundle: Bundle) = bundle.validity() + + override fun visitInline(inline: Inline) = inline.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1699,16 +1894,29 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Data { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Data(bundle = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Data(inline = it, _json = json) - } - - return Data(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Data(bundle = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Data(inline = 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 -> Data(_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() + } } } @@ -1728,30 +1936,43 @@ private constructor( } } - @NoAutoDetect class Bundle - @JsonCreator private constructor( - @JsonProperty("bundle_id") - @ExcludeMissing - private val bundleId: JsonField = JsonMissing.of(), - @JsonProperty("location") - @ExcludeMissing - private val location: JsonField = JsonMissing.of(), - @JsonProperty("runtime_context") - @ExcludeMissing - private val runtimeContext: JsonField = - JsonMissing.of(), - @JsonProperty("preview") - @ExcludeMissing - private val preview: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val bundleId: JsonField, + private val location: JsonField, + private val runtimeContext: JsonField, + private val preview: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("bundle_id") + @ExcludeMissing + bundleId: JsonField = JsonMissing.of(), + @JsonProperty("location") + @ExcludeMissing + location: JsonField = JsonMissing.of(), + @JsonProperty("runtime_context") + @ExcludeMissing + runtimeContext: JsonField = JsonMissing.of(), + @JsonProperty("preview") + @ExcludeMissing + preview: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(bundleId, location, runtimeContext, preview, type, mutableMapOf()) + + fun toCodeBundle(): CodeBundle = + CodeBundle.builder() + .bundleId(bundleId) + .location(location) + .runtimeContext(runtimeContext) + .preview(preview) + .build() + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -1780,8 +2001,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ - fun preview(): Optional = - Optional.ofNullable(preview.getNullable("preview")) + fun preview(): Optional = preview.getOptional("preview") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected @@ -1838,32 +2058,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toCodeBundle(): CodeBundle = - CodeBundle.builder() - .bundleId(bundleId) - .location(location) - .runtimeContext(runtimeContext) - .preview(preview) - .build() - - private var validated: Boolean = false - - fun validate(): Bundle = apply { - if (validated) { - return@apply - } - - bundleId() - location().validate() - runtimeContext().validate() - preview() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2030,10 +2233,47 @@ private constructor( checkRequired("runtimeContext", runtimeContext), preview, checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Bundle = apply { + if (validated) { + return@apply + } + + bundleId() + location().validate() + runtimeContext().validate() + preview() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (bundleId.asKnown().isPresent) 1 else 0) + + (location.asKnown().getOrNull()?.validity() ?: 0) + + (runtimeContext.asKnown().getOrNull()?.validity() ?: 0) + + (if (preview.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -2122,6 +2362,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2153,23 +2421,27 @@ private constructor( "Bundle{bundleId=$bundleId, location=$location, runtimeContext=$runtimeContext, preview=$preview, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Inline - @JsonCreator private constructor( - @JsonProperty("code") - @ExcludeMissing - private val code: JsonField = JsonMissing.of(), - @JsonProperty("runtime_context") - @ExcludeMissing - private val runtimeContext: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val code: JsonField, + private val runtimeContext: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("code") + @ExcludeMissing + code: JsonField = JsonMissing.of(), + @JsonProperty("runtime_context") + @ExcludeMissing + runtimeContext: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(code, runtimeContext, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -2216,25 +2488,18 @@ private constructor( * Unlike [type], this method doesn't throw if the JSON field has an unexpected * type. */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Inline = apply { - if (validated) { - return@apply - } - - code() - runtimeContext().validate() - type() - validated = true + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + fun toBuilder() = Builder().from(this) companion object { @@ -2346,25 +2611,60 @@ private constructor( checkRequired("code", code), checkRequired("runtimeContext", runtimeContext), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Inline = apply { + if (validated) { + return@apply + } + + code() + runtimeContext().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (code.asKnown().isPresent) 1 else 0) + + (runtimeContext.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class RuntimeContext - @JsonCreator private constructor( - @JsonProperty("runtime") - @ExcludeMissing - private val runtime: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val runtime: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("runtime") + @ExcludeMissing + runtime: JsonField = JsonMissing.of(), + @JsonProperty("version") + @ExcludeMissing + version: JsonField = JsonMissing.of(), + ) : this(runtime, version, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an * unexpected type or is unexpectedly missing or null (e.g. if the server @@ -2399,21 +2699,15 @@ private constructor( @ExcludeMissing fun _version(): JsonField = version + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): RuntimeContext = apply { - if (validated) { - return@apply - } - - runtime() - version() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2514,10 +2808,41 @@ private constructor( RuntimeContext( checkRequired("runtime", runtime), checkRequired("version", version), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): RuntimeContext = apply { + if (validated) { + return@apply + } + + runtime().validate() + version() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (runtime.asKnown().getOrNull()?.validity() ?: 0) + + (if (version.asKnown().isPresent) 1 else 0) + class Runtime @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -2617,6 +2942,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Runtime = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2736,6 +3089,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2852,6 +3233,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2883,20 +3291,19 @@ private constructor( "Code{data=$data, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Global - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(name, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -2925,21 +3332,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Global = apply { - if (validated) { - return@apply - } - - name() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3032,10 +3433,41 @@ private constructor( Global( checkRequired("name", name), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Global = apply { + if (validated) { + return@apply + } + + name() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -3120,6 +3552,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -3153,35 +3612,32 @@ private constructor( } /** JSON schema for the function's parameters and return type */ - @NoAutoDetect class FunctionSchema - @JsonCreator private constructor( - @JsonProperty("parameters") - @ExcludeMissing - private val parameters: JsonValue = JsonMissing.of(), - @JsonProperty("returns") @ExcludeMissing private val returns: JsonValue = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val parameters: JsonValue, + private val returns: JsonValue, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("parameters") @ExcludeMissing parameters: JsonValue = JsonMissing.of(), + @JsonProperty("returns") @ExcludeMissing returns: JsonValue = JsonMissing.of(), + ) : this(parameters, returns, mutableMapOf()) + @JsonProperty("parameters") @ExcludeMissing fun _parameters(): JsonValue = parameters @JsonProperty("returns") @ExcludeMissing fun _returns(): JsonValue = returns + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): FunctionSchema = apply { - if (validated) { - return@apply - } - - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3234,9 +3690,35 @@ private constructor( * Further updates to this [Builder] will not mutate the returned instance. */ fun build(): FunctionSchema = - FunctionSchema(parameters, returns, additionalProperties.toImmutable()) + FunctionSchema(parameters, returns, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): FunctionSchema = apply { + if (validated) { + return@apply + } + + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = 0 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3357,6 +3839,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): FunctionType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -3370,23 +3879,27 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class Origin - @JsonCreator private constructor( - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("internal") - @ExcludeMissing - private val internal_: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val objectId: JsonField, + private val objectType: JsonField, + private val internal_: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("object_id") + @ExcludeMissing + objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("internal") + @ExcludeMissing + internal_: JsonField = JsonMissing.of(), + ) : this(objectId, objectType, internal_, mutableMapOf()) + /** * Id of the object the function is originating from * @@ -3410,7 +3923,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun internal_(): Optional = Optional.ofNullable(internal_.getNullable("internal")) + fun internal_(): Optional = internal_.getOptional("internal") /** * Returns the raw JSON value of [objectId]. @@ -3435,22 +3948,15 @@ private constructor( */ @JsonProperty("internal") @ExcludeMissing fun _internal_(): JsonField = internal_ + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Origin = apply { - if (validated) { - return@apply - } - - objectId() - objectType() - internal_() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3572,10 +4078,43 @@ private constructor( checkRequired("objectId", objectId), checkRequired("objectType", objectType), internal_, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Origin = apply { + if (validated) { + return@apply + } + + objectId() + objectType().validate() + internal_() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (internal_.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionDeleteParams.kt index 28d9eacc..0fe9dab9 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionDeleteParams.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,26 +23,11 @@ private constructor( /** Function id */ fun functionId(): String = functionId - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> functionId - else -> "" - } - } + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -61,7 +45,6 @@ private constructor( } /** A builder for [FunctionDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var functionId: String? = null @@ -221,6 +204,19 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> functionId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionInvokeParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionInvokeParams.kt index 407d29b9..d5512a91 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionInvokeParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionInvokeParams.kt @@ -9,14 +9,13 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.allMaxBy import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -30,6 +29,7 @@ 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.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -149,48 +149,360 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) - override fun _headers(): Headers = additionalHeaders + companion object { - override fun _queryParams(): QueryParams = additionalQueryParams + /** + * Returns a mutable builder for constructing an instance of [FunctionInvokeParams]. + * + * The following fields are required: + * ```java + * .functionId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionInvokeParams]. */ + class Builder internal constructor() { + + private var functionId: 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(functionInvokeParams: FunctionInvokeParams) = apply { + functionId = functionInvokeParams.functionId + body = functionInvokeParams.body.toBuilder() + additionalHeaders = functionInvokeParams.additionalHeaders.toBuilder() + additionalQueryParams = functionInvokeParams.additionalQueryParams.toBuilder() + } + + /** Function id */ + fun functionId(functionId: String) = apply { this.functionId = functionId } + + /** + * 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: + * - [expected] + * - [input] + * - [messages] + * - [metadata] + * - [mode] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** The expected output of the function */ + fun expected(expected: JsonValue) = apply { body.expected(expected) } + + /** Argument to the function, which can be any JSON serializable value */ + fun input(input: JsonValue) = apply { body.input(input) } + + /** If the function is an LLM, additional messages to pass along to it */ + 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.ofSystem(system)`. */ + fun addMessage(system: Message.System) = apply { body.addMessage(system) } + + /** Alias for calling [addMessage] with `Message.ofUser(user)`. */ + fun addMessage(user: Message.User) = apply { body.addMessage(user) } + + /** Alias for calling [addMessage] with `Message.ofAssistant(assistant)`. */ + fun addMessage(assistant: Message.Assistant) = apply { body.addMessage(assistant) } + + /** Alias for calling [addMessage] with `Message.ofTool(tool)`. */ + fun addMessage(tool: Message.Tool) = apply { body.addMessage(tool) } + + /** Alias for calling [addMessage] with `Message.ofFunction(function)`. */ + fun addMessage(function: Message.Function) = apply { body.addMessage(function) } + + /** Alias for calling [addMessage] with `Message.ofFallback(fallback)`. */ + fun addMessage(fallback: Message.Fallback) = apply { body.addMessage(fallback) } + + /** Any relevant metadata */ + 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) } + + /** The mode format of the returned value (defaults to 'auto') */ + fun mode(mode: Mode?) = apply { body.mode(mode) } + + /** Alias for calling [Builder.mode] with `mode.orElse(null)`. */ + fun mode(mode: Optional) = mode(mode.getOrNull()) + + /** + * 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 { body.mode(mode) } + + /** Options for tracing the function call */ + fun parent(parent: Parent) = apply { body.parent(parent) } + + /** + * Sets [Builder.parent] to an arbitrary JSON value. + * + * You should usually call [Builder.parent] with a well-typed [Parent] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun parent(parent: JsonField) = apply { body.parent(parent) } + + /** Alias for calling [parent] with `Parent.ofSpanParentStruct(spanParentStruct)`. */ + fun parent(spanParentStruct: Parent.SpanParentStruct) = apply { + body.parent(spanParentStruct) + } + + /** Alias for calling [parent] with `Parent.ofString(string)`. */ + fun parent(string: String) = apply { body.parent(string) } + + /** + * Whether to stream the response. If true, results will be returned in the Braintrust SSE + * format. + */ + 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) } + + /** The version of the function */ + fun version(version: String) = apply { body.version(version) } + + /** + * Sets [Builder.version] to an arbitrary JSON value. + * + * You should usually call [Builder.version] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun version(version: JsonField) = apply { body.version(version) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - fun getPathParam(index: Int): String { - return when (index) { + 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 [FunctionInvokeParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .functionId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FunctionInvokeParams = + FunctionInvokeParams( + checkRequired("functionId", functionId), + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { 0 -> functionId else -> "" } - } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams /** The request to invoke a function */ - @NoAutoDetect class Body - @JsonCreator private constructor( - @JsonProperty("expected") - @ExcludeMissing - private val expected: JsonValue = JsonMissing.of(), - @JsonProperty("input") @ExcludeMissing private val input: JsonValue = JsonMissing.of(), - @JsonProperty("messages") - @ExcludeMissing - private val messages: JsonField> = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("mode") @ExcludeMissing private val mode: JsonField = JsonMissing.of(), - @JsonProperty("parent") - @ExcludeMissing - private val parent: JsonField = JsonMissing.of(), - @JsonProperty("stream") - @ExcludeMissing - private val stream: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val expected: JsonValue, + private val input: JsonValue, + private val messages: JsonField>, + private val metadata: JsonField, + private val mode: JsonField, + private val parent: JsonField, + private val stream: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("expected") @ExcludeMissing expected: JsonValue = JsonMissing.of(), + @JsonProperty("input") @ExcludeMissing input: JsonValue = JsonMissing.of(), + @JsonProperty("messages") + @ExcludeMissing + messages: JsonField> = JsonMissing.of(), + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), + @JsonProperty("mode") @ExcludeMissing mode: JsonField = JsonMissing.of(), + @JsonProperty("parent") @ExcludeMissing parent: JsonField = JsonMissing.of(), + @JsonProperty("stream") @ExcludeMissing stream: JsonField = JsonMissing.of(), + @JsonProperty("version") @ExcludeMissing version: JsonField = JsonMissing.of(), + ) : this(expected, input, messages, metadata, mode, parent, stream, version, mutableMapOf()) + /** The expected output of the function */ @JsonProperty("expected") @ExcludeMissing fun _expected(): JsonValue = expected @@ -203,8 +515,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * Any relevant metadata @@ -212,7 +523,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** * The mode format of the returned value (defaults to 'auto') @@ -220,7 +531,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun mode(): Optional = Optional.ofNullable(mode.getNullable("mode")) + fun mode(): Optional = mode.getOptional("mode") /** * Options for tracing the function call @@ -228,7 +539,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun parent(): Optional = Optional.ofNullable(parent.getNullable("parent")) + fun parent(): Optional = parent.getOptional("parent") /** * Whether to stream the response. If true, results will be returned in the Braintrust SSE @@ -237,7 +548,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun stream(): Optional = Optional.ofNullable(stream.getNullable("stream")) + fun stream(): Optional = stream.getOptional("stream") /** * The version of the function @@ -245,7 +556,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun version(): Optional = Optional.ofNullable(version.getNullable("version")) + fun version(): Optional = version.getOptional("version") /** * Returns the raw JSON value of [messages]. @@ -291,26 +602,16 @@ private constructor( */ @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - messages().ifPresent { it.forEach { it.validate() } } - metadata().ifPresent { it.validate() } - mode() - parent().ifPresent { it.validate() } - stream() - version() - validated = true + @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 { @@ -516,325 +817,65 @@ private constructor( parent, stream, version, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && expected == other.expected && input == other.input && messages == other.messages && metadata == other.metadata && mode == other.mode && parent == other.parent && stream == other.stream && version == other.version && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(expected, input, messages, metadata, mode, parent, stream, version, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{expected=$expected, input=$input, messages=$messages, metadata=$metadata, mode=$mode, parent=$parent, stream=$stream, version=$version, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [FunctionInvokeParams]. - * - * The following fields are required: - * ```java - * .functionId() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [FunctionInvokeParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var functionId: 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(functionInvokeParams: FunctionInvokeParams) = apply { - functionId = functionInvokeParams.functionId - body = functionInvokeParams.body.toBuilder() - additionalHeaders = functionInvokeParams.additionalHeaders.toBuilder() - additionalQueryParams = functionInvokeParams.additionalQueryParams.toBuilder() - } - - /** Function id */ - fun functionId(functionId: String) = apply { this.functionId = functionId } - - /** The expected output of the function */ - fun expected(expected: JsonValue) = apply { body.expected(expected) } - - /** Argument to the function, which can be any JSON serializable value */ - fun input(input: JsonValue) = apply { body.input(input) } - - /** If the function is an LLM, additional messages to pass along to it */ - 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.ofSystem(system)`. */ - fun addMessage(system: Message.System) = apply { body.addMessage(system) } - - /** Alias for calling [addMessage] with `Message.ofUser(user)`. */ - fun addMessage(user: Message.User) = apply { body.addMessage(user) } - - /** Alias for calling [addMessage] with `Message.ofAssistant(assistant)`. */ - fun addMessage(assistant: Message.Assistant) = apply { body.addMessage(assistant) } - - /** Alias for calling [addMessage] with `Message.ofTool(tool)`. */ - fun addMessage(tool: Message.Tool) = apply { body.addMessage(tool) } - - /** Alias for calling [addMessage] with `Message.ofFunction(function)`. */ - fun addMessage(function: Message.Function) = apply { body.addMessage(function) } - - /** Alias for calling [addMessage] with `Message.ofFallback(fallback)`. */ - fun addMessage(fallback: Message.Fallback) = apply { body.addMessage(fallback) } - - /** Any relevant metadata */ - 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) } - - /** The mode format of the returned value (defaults to 'auto') */ - fun mode(mode: Mode?) = apply { body.mode(mode) } - - /** Alias for calling [Builder.mode] with `mode.orElse(null)`. */ - fun mode(mode: Optional) = mode(mode.getOrNull()) - - /** - * 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 { body.mode(mode) } - - /** Options for tracing the function call */ - fun parent(parent: Parent) = apply { body.parent(parent) } - - /** - * Sets [Builder.parent] to an arbitrary JSON value. - * - * You should usually call [Builder.parent] with a well-typed [Parent] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun parent(parent: JsonField) = apply { body.parent(parent) } - - /** Alias for calling [parent] with `Parent.ofSpanParentStruct(spanParentStruct)`. */ - fun parent(spanParentStruct: Parent.SpanParentStruct) = apply { - body.parent(spanParentStruct) - } - - /** Alias for calling [parent] with `Parent.ofString(string)`. */ - fun parent(string: String) = apply { body.parent(string) } - - /** - * Whether to stream the response. If true, results will be returned in the Braintrust SSE - * format. - */ - 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) } - - /** The version of the function */ - fun version(version: String) = apply { body.version(version) } - - /** - * Sets [Builder.version] to an arbitrary JSON value. - * - * You should usually call [Builder.version] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun version(version: JsonField) = apply { body.version(version) } - - 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) - } + private var validated: Boolean = false - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun validate(): Body = apply { + if (validated) { + return@apply + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) + messages().ifPresent { it.forEach { it.validate() } } + metadata().ifPresent { it.validate() } + mode().ifPresent { it.validate() } + parent().ifPresent { it.validate() } + stream() + version() + validated = true } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } + /** + * Returns 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) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (mode.asKnown().getOrNull()?.validity() ?: 0) + + (parent.asKnown().getOrNull()?.validity() ?: 0) + + (if (stream.asKnown().isPresent) 1 else 0) + + (if (version.asKnown().isPresent) 1 else 0) - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + return /* spotless:off */ other is Body && expected == other.expected && input == other.input && messages == other.messages && metadata == other.metadata && mode == other.mode && parent == other.parent && stream == other.stream && version == other.version && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(expected, input, messages, metadata, mode, parent, stream, version, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [FunctionInvokeParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .functionId() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): FunctionInvokeParams = - FunctionInvokeParams( - checkRequired("functionId", functionId), - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{expected=$expected, input=$input, messages=$messages, metadata=$metadata, mode=$mode, parent=$parent, stream=$stream, version=$version, additionalProperties=$additionalProperties}" } @JsonDeserialize(using = Message.Deserializer::class) @@ -888,8 +929,8 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { system != null -> visitor.visitSystem(system) user != null -> visitor.visitUser(user) assistant != null -> visitor.visitAssistant(assistant) @@ -898,7 +939,6 @@ private constructor( fallback != null -> visitor.visitFallback(fallback) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -937,6 +977,40 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitSystem(system: System) = system.validity() + + override fun visitUser(user: User) = user.validity() + + override fun visitAssistant(assistant: Assistant) = assistant.validity() + + override fun visitTool(tool: Tool) = tool.validity() + + override fun visitFunction(function: Function) = function.validity() + + override fun visitFallback(fallback: Fallback) = fallback.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1011,32 +1085,40 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Message { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Message(system = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Message(user = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Message(assistant = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Message(tool = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Message(function = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Message(fallback = it, _json = json) - } - - return Message(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Message(system = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Message(user = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Message(assistant = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Message(tool = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Message(function = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Message(fallback = 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() + } } } @@ -1060,23 +1142,23 @@ private constructor( } } - @NoAutoDetect class System - @JsonCreator private constructor( - @JsonProperty("role") - @ExcludeMissing - private val role: JsonField = JsonMissing.of(), - @JsonProperty("content") - @ExcludeMissing - private val content: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val role: JsonField, + private val content: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("role") @ExcludeMissing role: JsonField = JsonMissing.of(), + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(role, content, name, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -1088,13 +1170,13 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun content(): Optional = Optional.ofNullable(content.getNullable("content")) + fun content(): Optional = content.getOptional("content") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun name(): Optional = name.getOptional("name") /** * Returns the raw JSON value of [role]. @@ -1117,22 +1199,15 @@ private constructor( */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): System = apply { - if (validated) { - return@apply - } - - role() - content() - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1237,10 +1312,43 @@ private constructor( checkRequired("role", role), content, name, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): System = apply { + if (validated) { + return@apply + } + + role().validate() + content() + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + + (if (content.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + class Role @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1325,6 +1433,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Role = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -1356,23 +1491,23 @@ private constructor( "System{role=$role, content=$content, name=$name, additionalProperties=$additionalProperties}" } - @NoAutoDetect class User - @JsonCreator private constructor( - @JsonProperty("role") - @ExcludeMissing - private val role: JsonField = JsonMissing.of(), - @JsonProperty("content") - @ExcludeMissing - private val content: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val role: JsonField, + private val content: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("role") @ExcludeMissing role: JsonField = JsonMissing.of(), + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(role, content, name, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -1384,13 +1519,13 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun content(): Optional = Optional.ofNullable(content.getNullable("content")) + fun content(): Optional = content.getOptional("content") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun name(): Optional = name.getOptional("name") /** * Returns the raw JSON value of [role]. @@ -1413,22 +1548,15 @@ private constructor( */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): User = apply { - if (validated) { - return@apply - } - - role() - content().ifPresent { it.validate() } - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1540,10 +1668,43 @@ private constructor( checkRequired("role", role), content, name, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): User = apply { + if (validated) { + return@apply + } + + role().validate() + content().ifPresent { it.validate() } + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + + (content.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + class Role @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1628,6 +1789,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Role = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -1664,13 +1852,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { text != null -> visitor.visitText(text) array != null -> visitor.visitArray(array) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1691,6 +1878,33 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitText(text: String) = 1 + + override fun visitArray(array: List) = + array.sumOf { it.validity().toInt() } + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1747,17 +1961,31 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Content { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef())?.let { - return Content(text = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(text = it, _json = json) + }, + tryDeserialize( + node, + jacksonTypeRef>(), + ) + ?.let { Content(array = 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 + // object). + 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() } - tryDeserialize(node, jacksonTypeRef>()) { - it.forEach { it.validate() } - } - ?.let { - return Content(array = it, _json = json) - } - - return Content(_json = json) } } @@ -1801,13 +2029,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { text != null -> visitor.visitText(text) image != null -> visitor.visitImage(image) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1817,18 +2044,46 @@ private constructor( } accept( - object : Visitor { - override fun visitText(text: ChatCompletionContentPartText) { - text.validate() - } + object : Visitor { + override fun visitText(text: ChatCompletionContentPartText) { + text.validate() + } + + override fun visitImage(image: ChatCompletionContentPartImage) { + image.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitText(text: ChatCompletionContentPartText) = + text.validity() - override fun visitImage(image: ChatCompletionContentPartImage) { - image.validate() - } + override fun visitImage(image: ChatCompletionContentPartImage) = + image.validity() + + override fun unknown(json: JsonValue?) = 0 } ) - validated = true - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -1897,20 +2152,38 @@ private constructor( ): ChatCompletionContentPart { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { - it.validate() - } - ?.let { - return ChatCompletionContentPart(text = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { - it.validate() - } - ?.let { - return ChatCompletionContentPart(image = it, _json = json) - } - - return ChatCompletionContentPart(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + ChatCompletionContentPart(text = it, _json = json) + }, + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + ChatCompletionContentPart(image = 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 -> ChatCompletionContentPart(_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() + } } } @@ -1954,30 +2227,31 @@ private constructor( "User{role=$role, content=$content, name=$name, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Assistant - @JsonCreator private constructor( - @JsonProperty("role") - @ExcludeMissing - private val role: JsonField = JsonMissing.of(), - @JsonProperty("content") - @ExcludeMissing - private val content: JsonField = JsonMissing.of(), - @JsonProperty("function_call") - @ExcludeMissing - private val functionCall: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("tool_calls") - @ExcludeMissing - private val toolCalls: JsonField> = - JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val role: JsonField, + private val content: JsonField, + private val functionCall: JsonField, + private val name: JsonField, + private val toolCalls: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("role") @ExcludeMissing role: 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("tool_calls") + @ExcludeMissing + toolCalls: JsonField> = JsonMissing.of(), + ) : this(role, content, functionCall, name, toolCalls, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -1989,27 +2263,26 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun content(): Optional = Optional.ofNullable(content.getNullable("content")) + fun content(): Optional = content.getOptional("content") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun functionCall(): Optional = - Optional.ofNullable(functionCall.getNullable("function_call")) + fun functionCall(): Optional = functionCall.getOptional("function_call") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun name(): Optional = name.getOptional("name") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ fun toolCalls(): Optional> = - Optional.ofNullable(toolCalls.getNullable("tool_calls")) + toolCalls.getOptional("tool_calls") /** * Returns the raw JSON value of [role]. @@ -2052,24 +2325,15 @@ private constructor( @ExcludeMissing fun _toolCalls(): JsonField> = toolCalls + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Assistant = apply { - if (validated) { - return@apply - } - - role() - content() - functionCall().ifPresent { it.validate() } - name() - toolCalls().ifPresent { it.forEach { it.validate() } } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2234,10 +2498,47 @@ private constructor( functionCall, name, (toolCalls ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Assistant = apply { + if (validated) { + return@apply + } + + role().validate() + content() + functionCall().ifPresent { it.validate() } + name() + toolCalls().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + + (if (content.asKnown().isPresent) 1 else 0) + + (functionCall.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (toolCalls.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + class Role @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -2322,6 +2623,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Role = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2335,20 +2663,21 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class FunctionCall - @JsonCreator private constructor( - @JsonProperty("arguments") - @ExcludeMissing - private val arguments: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val arguments: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("arguments") + @ExcludeMissing + arguments: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(arguments, name, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type * or is unexpectedly missing or null (e.g. if the server responded with an @@ -2381,21 +2710,15 @@ private constructor( */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): FunctionCall = apply { - if (validated) { - return@apply - } - - arguments() - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2490,10 +2813,41 @@ private constructor( FunctionCall( checkRequired("arguments", arguments), checkRequired("name", name), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): FunctionCall = apply { + if (validated) { + return@apply + } + + arguments() + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2530,23 +2884,25 @@ private constructor( "Assistant{role=$role, content=$content, functionCall=$functionCall, name=$name, toolCalls=$toolCalls, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Tool - @JsonCreator private constructor( - @JsonProperty("role") - @ExcludeMissing - private val role: JsonField = JsonMissing.of(), - @JsonProperty("content") - @ExcludeMissing - private val content: JsonField = JsonMissing.of(), - @JsonProperty("tool_call_id") - @ExcludeMissing - private val toolCallId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val role: JsonField, + private val content: JsonField, + private val toolCallId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("role") @ExcludeMissing role: JsonField = JsonMissing.of(), + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("tool_call_id") + @ExcludeMissing + toolCallId: JsonField = JsonMissing.of(), + ) : this(role, content, toolCallId, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -2558,14 +2914,13 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun content(): Optional = Optional.ofNullable(content.getNullable("content")) + fun content(): Optional = content.getOptional("content") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun toolCallId(): Optional = - Optional.ofNullable(toolCallId.getNullable("tool_call_id")) + fun toolCallId(): Optional = toolCallId.getOptional("tool_call_id") /** * Returns the raw JSON value of [role]. @@ -2591,22 +2946,15 @@ private constructor( @ExcludeMissing fun _toolCallId(): JsonField = toolCallId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Tool = apply { - if (validated) { - return@apply - } - - role() - content() - toolCallId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2713,10 +3061,43 @@ private constructor( checkRequired("role", role), content, toolCallId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Tool = apply { + if (validated) { + return@apply + } + + role().validate() + content() + toolCallId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + + (if (content.asKnown().isPresent) 1 else 0) + + (if (toolCallId.asKnown().isPresent) 1 else 0) + class Role @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -2801,6 +3182,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Role = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2832,23 +3240,23 @@ private constructor( "Tool{role=$role, content=$content, toolCallId=$toolCallId, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Function - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("role") - @ExcludeMissing - private val role: JsonField = JsonMissing.of(), - @JsonProperty("content") - @ExcludeMissing - private val content: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val role: JsonField, + private val content: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("role") @ExcludeMissing role: JsonField = JsonMissing.of(), + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + ) : this(name, role, content, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -2867,7 +3275,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun content(): Optional = Optional.ofNullable(content.getNullable("content")) + fun content(): Optional = content.getOptional("content") /** * Returns the raw JSON value of [name]. @@ -2890,22 +3298,15 @@ private constructor( */ @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Function = apply { - if (validated) { - return@apply - } - - name() - role() - content() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3012,10 +3413,43 @@ private constructor( checkRequired("name", name), checkRequired("role", role), content, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Function = apply { + if (validated) { + return@apply + } + + name() + role().validate() + content() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (role.asKnown().getOrNull()?.validity() ?: 0) + + (if (content.asKnown().isPresent) 1 else 0) + class Role @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -3100,6 +3534,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Role = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -3131,20 +3592,21 @@ private constructor( "Function{name=$name, role=$role, content=$content, additionalProperties=$additionalProperties}" } - @NoAutoDetect - class Fallback - @JsonCreator - private constructor( - @JsonProperty("role") - @ExcludeMissing - private val role: JsonField = JsonMissing.of(), - @JsonProperty("content") - @ExcludeMissing - private val content: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Fallback + private constructor( + private val role: JsonField, + private val content: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("role") @ExcludeMissing role: JsonField = JsonMissing.of(), + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + ) : this(role, content, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -3156,7 +3618,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun content(): Optional = Optional.ofNullable(content.getNullable("content")) + fun content(): Optional = content.getOptional("content") /** * Returns the raw JSON value of [role]. @@ -3172,21 +3634,15 @@ private constructor( */ @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Fallback = apply { - if (validated) { - return@apply - } - - role() - content() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3280,10 +3736,41 @@ private constructor( Fallback( checkRequired("role", role), content, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Fallback = apply { + if (validated) { + return@apply + } + + role().validate() + content() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + + (if (content.asKnown().isPresent) 1 else 0) + class Role @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -3368,6 +3855,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Role = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -3401,28 +3915,17 @@ private constructor( } /** Any relevant metadata */ - @NoAutoDetect class Metadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -3468,6 +3971,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -3573,6 +4104,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Mode = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -3614,13 +4172,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { spanParentStruct != null -> visitor.visitSpanParentStruct(spanParentStruct) string != null -> visitor.visitString(string) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -3641,6 +4198,33 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitSpanParentStruct(spanParentStruct: SpanParentStruct) = + spanParentStruct.validity() + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3699,15 +4283,28 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Parent { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Parent(spanParentStruct = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef())?.let { - return Parent(string = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Parent(spanParentStruct = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Parent(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 array). + 0 -> Parent(_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 Parent(_json = json) } } @@ -3728,26 +4325,31 @@ private constructor( } /** Span parent properties */ - @NoAutoDetect class SpanParentStruct - @JsonCreator private constructor( - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("propagated_event") - @ExcludeMissing - private val propagatedEvent: JsonField = JsonMissing.of(), - @JsonProperty("row_ids") - @ExcludeMissing - private val rowIds: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val objectId: JsonField, + private val objectType: JsonField, + private val propagatedEvent: JsonField, + private val rowIds: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("object_id") + @ExcludeMissing + objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("propagated_event") + @ExcludeMissing + propagatedEvent: JsonField = JsonMissing.of(), + @JsonProperty("row_ids") + @ExcludeMissing + rowIds: JsonField = JsonMissing.of(), + ) : this(objectId, objectType, propagatedEvent, rowIds, mutableMapOf()) + /** * The id of the container object you are logging to * @@ -3771,7 +4373,7 @@ private constructor( * if the server responded with an unexpected value). */ fun propagatedEvent(): Optional = - Optional.ofNullable(propagatedEvent.getNullable("propagated_event")) + propagatedEvent.getOptional("propagated_event") /** * Identifiers for the row to to log a subspan under @@ -3779,7 +4381,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun rowIds(): Optional = Optional.ofNullable(rowIds.getNullable("row_ids")) + fun rowIds(): Optional = rowIds.getOptional("row_ids") /** * Returns the raw JSON value of [objectId]. @@ -3816,23 +4418,15 @@ private constructor( */ @JsonProperty("row_ids") @ExcludeMissing fun _rowIds(): JsonField = rowIds + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SpanParentStruct = apply { - if (validated) { - return@apply - } - - objectId() - objectType() - propagatedEvent().ifPresent { it.validate() } - rowIds().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3970,10 +4564,45 @@ private constructor( checkRequired("objectType", objectType), propagatedEvent, rowIds, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): SpanParentStruct = apply { + if (validated) { + return@apply + } + + objectId() + objectType().validate() + propagatedEvent().ifPresent { it.validate() } + rowIds().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (propagatedEvent.asKnown().getOrNull()?.validity() ?: 0) + + (rowIds.asKnown().getOrNull()?.validity() ?: 0) + class ObjectType @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -4072,6 +4701,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ObjectType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -4086,28 +4742,17 @@ private constructor( } /** Include these properties in every span created under this parent */ - @NoAutoDetect class PropagatedEvent @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): PropagatedEvent = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -4159,6 +4804,36 @@ private constructor( PropagatedEvent(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): PropagatedEvent = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -4178,23 +4853,25 @@ private constructor( } /** Identifiers for the row to to log a subspan under */ - @NoAutoDetect class RowIds - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("root_span_id") - @ExcludeMissing - private val rootSpanId: JsonField = JsonMissing.of(), - @JsonProperty("span_id") - @ExcludeMissing - private val spanId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val rootSpanId: JsonField, + private val spanId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("root_span_id") + @ExcludeMissing + rootSpanId: JsonField = JsonMissing.of(), + @JsonProperty("span_id") + @ExcludeMissing + spanId: JsonField = JsonMissing.of(), + ) : this(id, rootSpanId, spanId, mutableMapOf()) + /** * The id of the row * @@ -4247,22 +4924,15 @@ private constructor( */ @JsonProperty("span_id") @ExcludeMissing fun _spanId(): JsonField = spanId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): RowIds = apply { - if (validated) { - return@apply - } - - id() - rootSpanId() - spanId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -4376,10 +5046,43 @@ private constructor( checkRequired("id", id), checkRequired("rootSpanId", rootSpanId), checkRequired("spanId", spanId), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): RowIds = apply { + if (validated) { + return@apply + } + + id() + rootSpanId() + spanId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (rootSpanId.asKnown().isPresent) 1 else 0) + + (if (spanId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionInvokeResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionInvokeResponse.kt index d7035b68..924b5b93 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionInvokeResponse.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionInvokeResponse.kt @@ -4,35 +4,28 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator +import java.util.Collections import java.util.Objects -@NoAutoDetect class FunctionInvokeResponse -@JsonCreator -private constructor( - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap() -) { +private constructor(private val additionalProperties: MutableMap) { - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false + @JsonCreator private constructor() : this(mutableMapOf()) - fun validate(): FunctionInvokeResponse = apply { - if (validated) { - return@apply - } - - validated = true + @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 { @@ -76,9 +69,34 @@ private constructor( * Further updates to this [Builder] will not mutate the returned instance. */ fun build(): FunctionInvokeResponse = - FunctionInvokeResponse(additionalProperties.toImmutable()) + FunctionInvokeResponse(additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): FunctionInvokeResponse = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = 0 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListPage.kt index 4f51a5ad..26550ec2 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListPage.kt @@ -2,167 +2,115 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.FunctionService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all functions. The functions are sorted by creation date, with the most recently-created - * functions coming first - */ +/** @see [FunctionService.list] */ class FunctionListPage private constructor( - private val functionsService: FunctionService, + private val service: FunctionService, private val params: FunctionListParams, - private val response: Response, + private val response: FunctionListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [FunctionListPageResponse], but gracefully handles missing data. + * + * @see [FunctionListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is FunctionListPage && functionsService == other.functionsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(functionsService, params, response) /* spotless:on */ - - override fun toString() = - "FunctionListPage{functionsService=$functionsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - FunctionListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - FunctionListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { functionsService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(functionsService: FunctionService, params: FunctionListParams, response: Response) = - FunctionListPage(functionsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): FunctionListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): FunctionListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [FunctionListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [FunctionListPage]. */ + class Builder internal constructor() { - companion object { + private var service: FunctionService? = null + private var params: FunctionListParams? = null + private var response: FunctionListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [FunctionListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(functionListPage: FunctionListPage) = apply { + service = functionListPage.service + params = functionListPage.params + response = functionListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: FunctionService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: FunctionListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: FunctionListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [FunctionListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FunctionListPage = + FunctionListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: FunctionListPage) : Iterable { @@ -183,4 +131,17 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is FunctionListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "FunctionListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListPageAsync.kt index 5979e5bf..77b7c749 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListPageAsync.kt @@ -2,174 +2,119 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.FunctionServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all functions. The functions are sorted by creation date, with the most recently-created - * functions coming first - */ +/** @see [FunctionServiceAsync.list] */ class FunctionListPageAsync private constructor( - private val functionsService: FunctionServiceAsync, + private val service: FunctionServiceAsync, private val params: FunctionListParams, - private val response: Response, + private val response: FunctionListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [FunctionListPageResponse], but gracefully handles missing data. + * + * @see [FunctionListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is FunctionListPageAsync && functionsService == other.functionsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(functionsService, params, response) /* spotless:on */ - - override fun toString() = - "FunctionListPageAsync{functionsService=$functionsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - FunctionListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - FunctionListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { functionsService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of( - functionsService: FunctionServiceAsync, - params: FunctionListParams, - response: Response, - ) = FunctionListPageAsync(functionsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): FunctionListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): FunctionListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [FunctionListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [FunctionListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: FunctionServiceAsync? = null + private var params: FunctionListParams? = null + private var response: FunctionListPageResponse? = null - /** - * Returns a mutable builder for constructing an instance of [FunctionListPageAsync]. - */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(functionListPageAsync: FunctionListPageAsync) = apply { + service = functionListPageAsync.service + params = functionListPageAsync.params + response = functionListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: FunctionServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: FunctionListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: FunctionListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [FunctionListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FunctionListPageAsync = + FunctionListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: FunctionListPageAsync) { @@ -197,4 +142,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is FunctionListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "FunctionListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListPageResponse.kt new file mode 100644 index 00000000..09acf2d6 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListPageResponse.kt @@ -0,0 +1,194 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class FunctionListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") + @ExcludeMissing + objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of function objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [FunctionListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(functionListPageResponse: FunctionListPageResponse) = apply { + objects = functionListPageResponse.objects.map { it.toMutableList() } + additionalProperties = functionListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of function objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [Function] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: Function) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FunctionListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FunctionListPageResponse = + FunctionListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): FunctionListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is FunctionListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FunctionListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListParams.kt index 534f5284..bfbc5441 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListParams.kt @@ -2,22 +2,10 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -96,35 +84,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - endingBefore?.let { put("ending_before", it) } - functionName?.let { put("function_name", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - orgName?.let { put("org_name", it) } - projectId?.let { put("project_id", it) } - projectName?.let { put("project_name", it) } - slug?.let { put("slug", it) } - startingAfter?.let { put("starting_after", it) } - version?.let { put("version", it) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -136,7 +95,6 @@ private constructor( } /** A builder for [FunctionListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var endingBefore: String? = null @@ -382,17 +340,43 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + endingBefore?.let { put("ending_before", it) } + functionName?.let { put("function_name", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + orgName?.let { put("org_name", it) } + projectId?.let { put("project_id", it) } + projectName?.let { put("project_name", it) } + slug?.let { put("slug", it) } + startingAfter?.let { put("starting_after", it) } + version?.let { put("version", it) } + putAll(additionalQueryParams) + } + .build() + /** * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -407,15 +391,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -431,7 +412,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -448,51 +428,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionReplaceParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionReplaceParams.kt index 78279e3e..79093cb3 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionReplaceParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionReplaceParams.kt @@ -9,14 +9,13 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.allMaxBy import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.braintrustdata.api.models.CodeBundle.* @@ -31,6 +30,7 @@ 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.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -196,529 +196,331 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("function_data") - @ExcludeMissing - private val functionData: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("slug") - @ExcludeMissing - private val slug: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("function_schema") - @ExcludeMissing - private val functionSchema: JsonField = JsonMissing.of(), - @JsonProperty("function_type") - @ExcludeMissing - private val functionType: JsonField = JsonMissing.of(), - @JsonProperty("origin") - @ExcludeMissing - private val origin: JsonField = JsonMissing.of(), - @JsonProperty("prompt_data") - @ExcludeMissing - private val promptData: JsonField = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + fun toBuilder() = Builder().from(this) - /** - * @throws BraintrustInvalidDataException 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 functionData(): FunctionData = functionData.getRequired("function_data") + companion object { /** - * Name of the prompt + * Returns a mutable builder for constructing an instance of [FunctionReplaceParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .functionData() + * .name() + * .projectId() + * .slug() + * ``` */ - fun name(): String = name.getRequired("name") + @JvmStatic fun builder() = Builder() + } - /** - * Unique identifier for the project that the prompt belongs under - * - * @throws BraintrustInvalidDataException 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 projectId(): String = projectId.getRequired("project_id") + /** A builder for [FunctionReplaceParams]. */ + class Builder internal constructor() { - /** - * Unique identifier for the prompt - * - * @throws BraintrustInvalidDataException 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 slug(): String = slug.getRequired("slug") + 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(functionReplaceParams: FunctionReplaceParams) = apply { + body = functionReplaceParams.body.toBuilder() + additionalHeaders = functionReplaceParams.additionalHeaders.toBuilder() + additionalQueryParams = functionReplaceParams.additionalQueryParams.toBuilder() + } /** - * Textual description of the prompt + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [functionData] + * - [name] + * - [projectId] + * - [slug] + * - [description] + * - etc. */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun body(body: Body) = apply { this.body = body.toBuilder() } + + fun functionData(functionData: FunctionData) = apply { body.functionData(functionData) } /** - * JSON schema for the function's parameters and return type + * Sets [Builder.functionData] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.functionData] with a well-typed [FunctionData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun functionSchema(): Optional = - Optional.ofNullable(functionSchema.getNullable("function_schema")) + fun functionData(functionData: JsonField) = apply { + body.functionData(functionData) + } - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun functionType(): Optional = - Optional.ofNullable(functionType.getNullable("function_type")) + /** Alias for calling [functionData] with `FunctionData.ofPrompt(prompt)`. */ + fun functionData(prompt: FunctionData.Prompt) = apply { body.functionData(prompt) } - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun origin(): Optional = Optional.ofNullable(origin.getNullable("origin")) + /** Alias for calling [functionData] with `FunctionData.ofCode(code)`. */ + fun functionData(code: FunctionData.Code) = apply { body.functionData(code) } - /** - * The prompt, model, and its parameters - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun promptData(): Optional = - Optional.ofNullable(promptData.getNullable("prompt_data")) + /** Alias for calling [functionData] with `FunctionData.ofGlobal(global)`. */ + fun functionData(global: FunctionData.Global) = apply { body.functionData(global) } - /** - * A list of tags for the prompt - * - * @throws BraintrustInvalidDataException 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")) + /** Name of the prompt */ + fun name(name: String) = apply { body.name(name) } /** - * Returns the raw JSON value of [functionData]. + * Sets [Builder.name] to an arbitrary JSON value. * - * Unlike [functionData], this method doesn't throw if the JSON field has an unexpected - * type. + * 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. */ - @JsonProperty("function_data") - @ExcludeMissing - fun _functionData(): JsonField = functionData + fun name(name: JsonField) = apply { body.name(name) } + + /** Unique identifier for the project that the prompt belongs under */ + fun projectId(projectId: String) = apply { body.projectId(projectId) } /** - * Returns the raw JSON value of [name]. + * Sets [Builder.projectId] to an arbitrary JSON value. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } + + /** Unique identifier for the prompt */ + fun slug(slug: String) = apply { body.slug(slug) } /** - * Returns the raw JSON value of [projectId]. + * Sets [Builder.slug] to an arbitrary JSON value. * - * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.slug] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId + fun slug(slug: JsonField) = apply { body.slug(slug) } + + /** Textual description of the prompt */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) /** - * Returns the raw JSON value of [slug]. + * Sets [Builder.description] to an arbitrary JSON value. * - * Unlike [slug], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("slug") @ExcludeMissing fun _slug(): JsonField = slug + fun description(description: JsonField) = apply { body.description(description) } + + /** JSON schema for the function's parameters and return type */ + fun functionSchema(functionSchema: FunctionSchema?) = apply { + body.functionSchema(functionSchema) + } + + /** Alias for calling [Builder.functionSchema] with `functionSchema.orElse(null)`. */ + fun functionSchema(functionSchema: Optional) = + functionSchema(functionSchema.getOrNull()) /** - * Returns the raw JSON value of [description]. + * Sets [Builder.functionSchema] to an arbitrary JSON value. * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.functionSchema] with a well-typed [FunctionSchema] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description + fun functionSchema(functionSchema: JsonField) = apply { + body.functionSchema(functionSchema) + } + + fun functionType(functionType: FunctionType?) = apply { body.functionType(functionType) } + + /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ + fun functionType(functionType: Optional) = + functionType(functionType.getOrNull()) /** - * Returns the raw JSON value of [functionSchema]. + * Sets [Builder.functionType] to an arbitrary JSON value. * - * Unlike [functionSchema], this method doesn't throw if the JSON field has an unexpected - * type. + * You should usually call [Builder.functionType] with a well-typed [FunctionType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("function_schema") - @ExcludeMissing - fun _functionSchema(): JsonField = functionSchema + fun functionType(functionType: JsonField) = apply { + body.functionType(functionType) + } + + fun origin(origin: Origin?) = apply { body.origin(origin) } + + /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ + fun origin(origin: Optional) = origin(origin.getOrNull()) /** - * Returns the raw JSON value of [functionType]. + * Sets [Builder.origin] to an arbitrary JSON value. * - * Unlike [functionType], this method doesn't throw if the JSON field has an unexpected - * type. + * You should usually call [Builder.origin] with a well-typed [Origin] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("function_type") - @ExcludeMissing - fun _functionType(): JsonField = functionType + fun origin(origin: JsonField) = apply { body.origin(origin) } + + /** The prompt, model, and its parameters */ + fun promptData(promptData: PromptData?) = apply { body.promptData(promptData) } + + /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ + fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) /** - * Returns the raw JSON value of [origin]. + * Sets [Builder.promptData] to an arbitrary JSON value. * - * Unlike [origin], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.promptData] with a well-typed [PromptData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("origin") @ExcludeMissing fun _origin(): JsonField = origin + fun promptData(promptData: JsonField) = apply { body.promptData(promptData) } + + /** A list of tags for the prompt */ + fun tags(tags: List?) = apply { body.tags(tags) } + + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) /** - * Returns the raw JSON value of [promptData]. + * Sets [Builder.tags] to an arbitrary JSON value. * - * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.tags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("prompt_data") - @ExcludeMissing - fun _promptData(): JsonField = promptData + fun tags(tags: JsonField>) = apply { body.tags(tags) } /** - * Returns the raw JSON value of [tags]. + * Adds a single [String] to [tags]. * - * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + fun addTag(tag: String) = apply { body.addTag(tag) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - functionData().validate() - name() - projectId() - slug() - description() - functionSchema().ifPresent { it.validate() } - functionType() - origin().ifPresent { it.validate() } - promptData().ifPresent { it.validate() } - tags() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .functionData() - * .name() - * .projectId() - * .slug() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) } - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var functionData: JsonField? = null - private var name: JsonField? = null - private var projectId: JsonField? = null - private var slug: JsonField? = null - private var description: JsonField = JsonMissing.of() - private var functionSchema: JsonField = JsonMissing.of() - private var functionType: JsonField = JsonMissing.of() - private var origin: JsonField = JsonMissing.of() - private var promptData: JsonField = JsonMissing.of() - private var tags: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - functionData = body.functionData - name = body.name - projectId = body.projectId - slug = body.slug - description = body.description - functionSchema = body.functionSchema - functionType = body.functionType - origin = body.origin - promptData = body.promptData - tags = body.tags.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } - - fun functionData(functionData: FunctionData) = functionData(JsonField.of(functionData)) - - /** - * Sets [Builder.functionData] to an arbitrary JSON value. - * - * You should usually call [Builder.functionData] with a well-typed [FunctionData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun functionData(functionData: JsonField) = apply { - this.functionData = functionData - } - - /** Alias for calling [functionData] with `FunctionData.ofPrompt(prompt)`. */ - fun functionData(prompt: FunctionData.Prompt) = - functionData(FunctionData.ofPrompt(prompt)) - - /** Alias for calling [functionData] with `FunctionData.ofCode(code)`. */ - fun functionData(code: FunctionData.Code) = functionData(FunctionData.ofCode(code)) - - /** Alias for calling [functionData] with `FunctionData.ofGlobal(global)`. */ - fun functionData(global: FunctionData.Global) = - functionData(FunctionData.ofGlobal(global)) - - /** Name of the prompt */ - 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 } - - /** Unique identifier for the project that the prompt belongs under */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - - /** - * Sets [Builder.projectId] to an arbitrary JSON value. - * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } - - /** Unique identifier for the prompt */ - fun slug(slug: String) = slug(JsonField.of(slug)) - - /** - * Sets [Builder.slug] to an arbitrary JSON value. - * - * You should usually call [Builder.slug] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun slug(slug: JsonField) = apply { this.slug = slug } - - /** Textual description of the prompt */ - fun description(description: String?) = description(JsonField.ofNullable(description)) - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } - - /** JSON schema for the function's parameters and return type */ - fun functionSchema(functionSchema: FunctionSchema?) = - functionSchema(JsonField.ofNullable(functionSchema)) - - /** Alias for calling [Builder.functionSchema] with `functionSchema.orElse(null)`. */ - fun functionSchema(functionSchema: Optional) = - functionSchema(functionSchema.getOrNull()) - - /** - * Sets [Builder.functionSchema] to an arbitrary JSON value. - * - * You should usually call [Builder.functionSchema] with a well-typed [FunctionSchema] - * value instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun functionSchema(functionSchema: JsonField) = apply { - this.functionSchema = functionSchema + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - fun functionType(functionType: FunctionType?) = - functionType(JsonField.ofNullable(functionType)) + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ - fun functionType(functionType: Optional) = - functionType(functionType.getOrNull()) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** - * Sets [Builder.functionType] to an arbitrary JSON value. - * - * You should usually call [Builder.functionType] with a well-typed [FunctionType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun functionType(functionType: JsonField) = apply { - this.functionType = functionType - } + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - fun origin(origin: Origin?) = origin(JsonField.ofNullable(origin)) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ - fun origin(origin: Optional) = origin(origin.getOrNull()) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** - * Sets [Builder.origin] to an arbitrary JSON value. - * - * You should usually call [Builder.origin] with a well-typed [Origin] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun origin(origin: JsonField) = apply { this.origin = origin } + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** The prompt, model, and its parameters */ - fun promptData(promptData: PromptData?) = promptData(JsonField.ofNullable(promptData)) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ - fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** - * Sets [Builder.promptData] to an arbitrary JSON value. - * - * You should usually call [Builder.promptData] with a well-typed [PromptData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun promptData(promptData: JsonField) = apply { - this.promptData = promptData - } + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** A list of tags for the prompt */ - fun tags(tags: List?) = tags(JsonField.ofNullable(tags)) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ - fun tags(tags: Optional>) = tags(tags.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.tags] to an arbitrary JSON value. - * - * You should usually call [Builder.tags] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun tags(tags: JsonField>) = apply { - this.tags = tags.map { it.toMutableList() } - } + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Adds a single [String] to [tags]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addTag(tag: String) = apply { - tags = - (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } - } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .functionData() - * .name() - * .projectId() - * .slug() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("functionData", functionData), - checkRequired("name", name), - checkRequired("projectId", projectId), - checkRequired("slug", slug), - description, - functionSchema, - functionType, - origin, - promptData, - (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && functionData == other.functionData && name == other.name && projectId == other.projectId && slug == other.slug && description == other.description && functionSchema == other.functionSchema && functionType == other.functionType && origin == other.origin && promptData == other.promptData && tags == other.tags && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(functionData, name, projectId, slug, description, functionSchema, functionType, origin, promptData, tags, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{functionData=$functionData, name=$name, projectId=$projectId, slug=$slug, description=$description, functionSchema=$functionSchema, functionType=$functionType, origin=$origin, promptData=$promptData, tags=$tags, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [FunctionReplaceParams]. + * Returns an immutable instance of [FunctionReplaceParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java @@ -727,321 +529,577 @@ private constructor( * .projectId() * .slug() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): FunctionReplaceParams = + FunctionReplaceParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [FunctionReplaceParams]. */ - @NoAutoDetect - class Builder internal constructor() { + fun _body(): Body = body - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + override fun _headers(): Headers = additionalHeaders - @JvmSynthetic - internal fun from(functionReplaceParams: FunctionReplaceParams) = apply { - body = functionReplaceParams.body.toBuilder() - additionalHeaders = functionReplaceParams.additionalHeaders.toBuilder() - additionalQueryParams = functionReplaceParams.additionalQueryParams.toBuilder() - } + override fun _queryParams(): QueryParams = additionalQueryParams - fun functionData(functionData: FunctionData) = apply { body.functionData(functionData) } + class Body + private constructor( + private val functionData: JsonField, + private val name: JsonField, + private val projectId: JsonField, + private val slug: JsonField, + private val description: JsonField, + private val functionSchema: JsonField, + private val functionType: JsonField, + private val origin: JsonField, + private val promptData: JsonField, + private val tags: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("function_data") + @ExcludeMissing + functionData: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") + @ExcludeMissing + projectId: JsonField = JsonMissing.of(), + @JsonProperty("slug") @ExcludeMissing slug: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("function_schema") + @ExcludeMissing + functionSchema: JsonField = JsonMissing.of(), + @JsonProperty("function_type") + @ExcludeMissing + functionType: JsonField = JsonMissing.of(), + @JsonProperty("origin") @ExcludeMissing origin: JsonField = JsonMissing.of(), + @JsonProperty("prompt_data") + @ExcludeMissing + promptData: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this( + functionData, + name, + projectId, + slug, + description, + functionSchema, + functionType, + origin, + promptData, + tags, + mutableMapOf(), + ) /** - * Sets [Builder.functionData] to an arbitrary JSON value. + * @throws BraintrustInvalidDataException 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 functionData(): FunctionData = functionData.getRequired("function_data") + + /** + * Name of the prompt * - * You should usually call [Builder.functionData] with a well-typed [FunctionData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException 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 functionData(functionData: JsonField) = apply { - body.functionData(functionData) - } + fun name(): String = name.getRequired("name") - /** Alias for calling [functionData] with `FunctionData.ofPrompt(prompt)`. */ - fun functionData(prompt: FunctionData.Prompt) = apply { body.functionData(prompt) } + /** + * Unique identifier for the project that the prompt belongs under + * + * @throws BraintrustInvalidDataException 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 projectId(): String = projectId.getRequired("project_id") - /** Alias for calling [functionData] with `FunctionData.ofCode(code)`. */ - fun functionData(code: FunctionData.Code) = apply { body.functionData(code) } + /** + * Unique identifier for the prompt + * + * @throws BraintrustInvalidDataException 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 slug(): String = slug.getRequired("slug") - /** Alias for calling [functionData] with `FunctionData.ofGlobal(global)`. */ - fun functionData(global: FunctionData.Global) = apply { body.functionData(global) } + /** + * Textual description of the prompt + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") - /** Name of the prompt */ - fun name(name: String) = apply { body.name(name) } + /** + * JSON schema for the function's parameters and return type + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun functionSchema(): Optional = + functionSchema.getOptional("function_schema") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun functionType(): Optional = functionType.getOptional("function_type") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun origin(): Optional = origin.getOptional("origin") + + /** + * The prompt, model, and its parameters + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun promptData(): Optional = promptData.getOptional("prompt_data") /** - * Sets [Builder.name] to an arbitrary JSON value. + * A list of tags for the prompt * - * 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. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun name(name: JsonField) = apply { body.name(name) } - - /** Unique identifier for the project that the prompt belongs under */ - fun projectId(projectId: String) = apply { body.projectId(projectId) } + fun tags(): Optional> = tags.getOptional("tags") /** - * Sets [Builder.projectId] to an arbitrary JSON value. + * Returns the raw JSON value of [functionData]. * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [functionData], this method doesn't throw if the JSON field has an unexpected + * type. */ - fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } - - /** Unique identifier for the prompt */ - fun slug(slug: String) = apply { body.slug(slug) } + @JsonProperty("function_data") + @ExcludeMissing + fun _functionData(): JsonField = functionData /** - * Sets [Builder.slug] to an arbitrary JSON value. + * Returns the raw JSON value of [name]. * - * You should usually call [Builder.slug] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. */ - fun slug(slug: JsonField) = apply { body.slug(slug) } - - /** Textual description of the prompt */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name /** - * Sets [Builder.description] to an arbitrary JSON value. + * Returns the raw JSON value of [projectId]. * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. */ - fun description(description: JsonField) = apply { body.description(description) } - - /** JSON schema for the function's parameters and return type */ - fun functionSchema(functionSchema: FunctionSchema?) = apply { - body.functionSchema(functionSchema) - } - - /** Alias for calling [Builder.functionSchema] with `functionSchema.orElse(null)`. */ - fun functionSchema(functionSchema: Optional) = - functionSchema(functionSchema.getOrNull()) + @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId /** - * Sets [Builder.functionSchema] to an arbitrary JSON value. + * Returns the raw JSON value of [slug]. * - * You should usually call [Builder.functionSchema] with a well-typed [FunctionSchema] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * Unlike [slug], this method doesn't throw if the JSON field has an unexpected type. */ - fun functionSchema(functionSchema: JsonField) = apply { - body.functionSchema(functionSchema) - } - - fun functionType(functionType: FunctionType?) = apply { body.functionType(functionType) } - - /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ - fun functionType(functionType: Optional) = - functionType(functionType.getOrNull()) + @JsonProperty("slug") @ExcludeMissing fun _slug(): JsonField = slug /** - * Sets [Builder.functionType] to an arbitrary JSON value. + * Returns the raw JSON value of [description]. * - * You should usually call [Builder.functionType] with a well-typed [FunctionType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. */ - fun functionType(functionType: JsonField) = apply { - body.functionType(functionType) - } - - fun origin(origin: Origin?) = apply { body.origin(origin) } - - /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ - fun origin(origin: Optional) = origin(origin.getOrNull()) + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description /** - * Sets [Builder.origin] to an arbitrary JSON value. + * Returns the raw JSON value of [functionSchema]. * - * You should usually call [Builder.origin] with a well-typed [Origin] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [functionSchema], this method doesn't throw if the JSON field has an unexpected + * type. */ - fun origin(origin: JsonField) = apply { body.origin(origin) } - - /** The prompt, model, and its parameters */ - fun promptData(promptData: PromptData?) = apply { body.promptData(promptData) } - - /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ - fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) + @JsonProperty("function_schema") + @ExcludeMissing + fun _functionSchema(): JsonField = functionSchema /** - * Sets [Builder.promptData] to an arbitrary JSON value. + * Returns the raw JSON value of [functionType]. * - * You should usually call [Builder.promptData] with a well-typed [PromptData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * Unlike [functionType], this method doesn't throw if the JSON field has an unexpected + * type. */ - fun promptData(promptData: JsonField) = apply { body.promptData(promptData) } - - /** A list of tags for the prompt */ - fun tags(tags: List?) = apply { body.tags(tags) } + @JsonProperty("function_type") + @ExcludeMissing + fun _functionType(): JsonField = functionType - /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ - fun tags(tags: Optional>) = tags(tags.getOrNull()) + /** + * Returns the raw JSON value of [origin]. + * + * Unlike [origin], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("origin") @ExcludeMissing fun _origin(): JsonField = origin /** - * Sets [Builder.tags] to an arbitrary JSON value. + * Returns the raw JSON value of [promptData]. * - * You should usually call [Builder.tags] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. */ - fun tags(tags: JsonField>) = apply { body.tags(tags) } + @JsonProperty("prompt_data") + @ExcludeMissing + fun _promptData(): JsonField = promptData /** - * Adds a single [String] to [tags]. + * Returns the raw JSON value of [tags]. * - * @throws IllegalStateException if the field was previously set to a non-list. + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. */ - fun addTag(tag: String) = apply { body.addTag(tag) } + @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) + @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 + * .functionData() + * .name() + * .projectId() + * .slug() + * ``` + */ + @JvmStatic fun builder() = Builder() } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var functionData: JsonField? = null + private var name: JsonField? = null + private var projectId: JsonField? = null + private var slug: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var functionSchema: JsonField = JsonMissing.of() + private var functionType: JsonField = JsonMissing.of() + private var origin: JsonField = JsonMissing.of() + private var promptData: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + functionData = body.functionData + name = body.name + projectId = body.projectId + slug = body.slug + description = body.description + functionSchema = body.functionSchema + functionType = body.functionType + origin = body.origin + promptData = body.promptData + tags = body.tags.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + fun functionData(functionData: FunctionData) = functionData(JsonField.of(functionData)) + + /** + * Sets [Builder.functionData] to an arbitrary JSON value. + * + * You should usually call [Builder.functionData] with a well-typed [FunctionData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun functionData(functionData: JsonField) = apply { + this.functionData = functionData + } + + /** Alias for calling [functionData] with `FunctionData.ofPrompt(prompt)`. */ + fun functionData(prompt: FunctionData.Prompt) = + functionData(FunctionData.ofPrompt(prompt)) + + /** Alias for calling [functionData] with `FunctionData.ofCode(code)`. */ + fun functionData(code: FunctionData.Code) = functionData(FunctionData.ofCode(code)) + + /** Alias for calling [functionData] with `FunctionData.ofGlobal(global)`. */ + fun functionData(global: FunctionData.Global) = + functionData(FunctionData.ofGlobal(global)) + + /** Name of the prompt */ + 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 } + + /** Unique identifier for the project that the prompt belongs under */ + fun projectId(projectId: String) = projectId(JsonField.of(projectId)) + + /** + * Sets [Builder.projectId] to an arbitrary JSON value. + * + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun projectId(projectId: JsonField) = apply { this.projectId = projectId } + + /** Unique identifier for the prompt */ + fun slug(slug: String) = slug(JsonField.of(slug)) + + /** + * Sets [Builder.slug] to an arbitrary JSON value. + * + * You should usually call [Builder.slug] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun slug(slug: JsonField) = apply { this.slug = slug } + + /** Textual description of the prompt */ + fun description(description: String?) = description(JsonField.ofNullable(description)) - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) - } + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** JSON schema for the function's parameters and return type */ + fun functionSchema(functionSchema: FunctionSchema?) = + functionSchema(JsonField.ofNullable(functionSchema)) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** Alias for calling [Builder.functionSchema] with `functionSchema.orElse(null)`. */ + fun functionSchema(functionSchema: Optional) = + functionSchema(functionSchema.getOrNull()) - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Sets [Builder.functionSchema] to an arbitrary JSON value. + * + * You should usually call [Builder.functionSchema] with a well-typed [FunctionSchema] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun functionSchema(functionSchema: JsonField) = apply { + this.functionSchema = functionSchema + } - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + fun functionType(functionType: FunctionType?) = + functionType(JsonField.ofNullable(functionType)) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ + fun functionType(functionType: Optional) = + functionType(functionType.getOrNull()) - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Sets [Builder.functionType] to an arbitrary JSON value. + * + * You should usually call [Builder.functionType] with a well-typed [FunctionType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun functionType(functionType: JsonField) = apply { + this.functionType = functionType + } - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + fun origin(origin: Origin?) = origin(JsonField.ofNullable(origin)) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ + fun origin(origin: Optional) = origin(origin.getOrNull()) - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** + * Sets [Builder.origin] to an arbitrary JSON value. + * + * You should usually call [Builder.origin] with a well-typed [Origin] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun origin(origin: JsonField) = apply { this.origin = origin } - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** The prompt, model, and its parameters */ + fun promptData(promptData: PromptData?) = promptData(JsonField.ofNullable(promptData)) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ + fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + /** + * Sets [Builder.promptData] to an arbitrary JSON value. + * + * You should usually call [Builder.promptData] with a well-typed [PromptData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun promptData(promptData: JsonField) = apply { + this.promptData = promptData + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + /** A list of tags for the prompt */ + fun tags(tags: List?) = tags(JsonField.ofNullable(tags)) - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** + * Sets [Builder.tags] to an arbitrary JSON value. + * + * You should usually call [Builder.tags] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tags(tags: JsonField>) = apply { + this.tags = tags.map { it.toMutableList() } + } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { + tags = + (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .functionData() + * .name() + * .projectId() + * .slug() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("functionData", functionData), + checkRequired("name", name), + checkRequired("projectId", projectId), + checkRequired("slug", slug), + description, + functionSchema, + functionType, + origin, + promptData, + (tags ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + private var validated: Boolean = false - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + fun validate(): Body = apply { + if (validated) { + return@apply + } - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + functionData().validate() + name() + projectId() + slug() + description() + functionSchema().ifPresent { it.validate() } + functionType().ifPresent { it.validate() } + origin().ifPresent { it.validate() } + promptData().ifPresent { it.validate() } + tags() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + /** - * Returns an immutable instance of [FunctionReplaceParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .functionData() - * .name() - * .projectId() - * .slug() - * ``` + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * @throws IllegalStateException if any required field is unset. + * Used for best match union deserialization. */ - fun build(): FunctionReplaceParams = - FunctionReplaceParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + @JvmSynthetic + internal fun validity(): Int = + (functionData.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (slug.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (functionSchema.asKnown().getOrNull()?.validity() ?: 0) + + (functionType.asKnown().getOrNull()?.validity() ?: 0) + + (origin.asKnown().getOrNull()?.validity() ?: 0) + + (promptData.asKnown().getOrNull()?.validity() ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && functionData == other.functionData && name == other.name && projectId == other.projectId && slug == other.slug && description == other.description && functionSchema == other.functionSchema && functionType == other.functionType && origin == other.origin && promptData == other.promptData && tags == other.tags && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(functionData, name, projectId, slug, description, functionSchema, functionType, origin, promptData, tags, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{functionData=$functionData, name=$name, projectId=$projectId, slug=$slug, description=$description, functionSchema=$functionSchema, functionType=$functionType, origin=$origin, promptData=$promptData, tags=$tags, additionalProperties=$additionalProperties}" } @JsonDeserialize(using = FunctionData.Deserializer::class) @@ -1074,14 +1132,13 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { prompt != null -> visitor.visitPrompt(prompt) code != null -> visitor.visitCode(code) global != null -> visitor.visitGlobal(global) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1108,6 +1165,34 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitPrompt(prompt: Prompt) = prompt.validity() + + override fun visitCode(code: Code) = code.validity() + + override fun visitGlobal(global: Global) = global.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1168,20 +1253,31 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): FunctionData { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return FunctionData(prompt = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return FunctionData(code = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return FunctionData(global = it, _json = json) - } - - return FunctionData(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionData(prompt = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionData(code = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionData(global = 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 -> FunctionData(_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() + } } } @@ -1202,17 +1298,17 @@ private constructor( } } - @NoAutoDetect class Prompt - @JsonCreator private constructor( - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of() + ) : this(type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -1227,20 +1323,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Prompt = apply { - if (validated) { - return@apply - } - - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1315,9 +1406,37 @@ private constructor( * @throws IllegalStateException if any required field is unset. */ fun build(): Prompt = - Prompt(checkRequired("type", type), additionalProperties.toImmutable()) + Prompt(checkRequired("type", type), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Prompt = apply { + if (validated) { + return@apply + } + + type().validate() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1402,6 +1521,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -1433,20 +1579,19 @@ private constructor( "Prompt{type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Code - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -1475,21 +1620,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Code = apply { - if (validated) { - return@apply - } - - data().validate() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1588,10 +1727,41 @@ private constructor( Code( checkRequired("data", data), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Code = apply { + if (validated) { + return@apply + } + + data().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (data.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + @JsonDeserialize(using = Data.Deserializer::class) @JsonSerialize(using = Data.Serializer::class) class Data @@ -1615,13 +1785,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { bundle != null -> visitor.visitBundle(bundle) inline != null -> visitor.visitInline(inline) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1644,6 +1813,32 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitBundle(bundle: Bundle) = bundle.validity() + + override fun visitInline(inline: Inline) = inline.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1699,16 +1894,29 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Data { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Data(bundle = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Data(inline = it, _json = json) - } - - return Data(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Data(bundle = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Data(inline = 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 -> Data(_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() + } } } @@ -1728,30 +1936,43 @@ private constructor( } } - @NoAutoDetect class Bundle - @JsonCreator private constructor( - @JsonProperty("bundle_id") - @ExcludeMissing - private val bundleId: JsonField = JsonMissing.of(), - @JsonProperty("location") - @ExcludeMissing - private val location: JsonField = JsonMissing.of(), - @JsonProperty("runtime_context") - @ExcludeMissing - private val runtimeContext: JsonField = - JsonMissing.of(), - @JsonProperty("preview") - @ExcludeMissing - private val preview: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val bundleId: JsonField, + private val location: JsonField, + private val runtimeContext: JsonField, + private val preview: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("bundle_id") + @ExcludeMissing + bundleId: JsonField = JsonMissing.of(), + @JsonProperty("location") + @ExcludeMissing + location: JsonField = JsonMissing.of(), + @JsonProperty("runtime_context") + @ExcludeMissing + runtimeContext: JsonField = JsonMissing.of(), + @JsonProperty("preview") + @ExcludeMissing + preview: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(bundleId, location, runtimeContext, preview, type, mutableMapOf()) + + fun toCodeBundle(): CodeBundle = + CodeBundle.builder() + .bundleId(bundleId) + .location(location) + .runtimeContext(runtimeContext) + .preview(preview) + .build() + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -1780,8 +2001,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ - fun preview(): Optional = - Optional.ofNullable(preview.getNullable("preview")) + fun preview(): Optional = preview.getOptional("preview") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected @@ -1838,32 +2058,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toCodeBundle(): CodeBundle = - CodeBundle.builder() - .bundleId(bundleId) - .location(location) - .runtimeContext(runtimeContext) - .preview(preview) - .build() - - private var validated: Boolean = false - - fun validate(): Bundle = apply { - if (validated) { - return@apply - } - - bundleId() - location().validate() - runtimeContext().validate() - preview() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2030,10 +2233,47 @@ private constructor( checkRequired("runtimeContext", runtimeContext), preview, checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Bundle = apply { + if (validated) { + return@apply + } + + bundleId() + location().validate() + runtimeContext().validate() + preview() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (bundleId.asKnown().isPresent) 1 else 0) + + (location.asKnown().getOrNull()?.validity() ?: 0) + + (runtimeContext.asKnown().getOrNull()?.validity() ?: 0) + + (if (preview.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -2122,6 +2362,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2153,23 +2421,27 @@ private constructor( "Bundle{bundleId=$bundleId, location=$location, runtimeContext=$runtimeContext, preview=$preview, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Inline - @JsonCreator private constructor( - @JsonProperty("code") - @ExcludeMissing - private val code: JsonField = JsonMissing.of(), - @JsonProperty("runtime_context") - @ExcludeMissing - private val runtimeContext: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val code: JsonField, + private val runtimeContext: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("code") + @ExcludeMissing + code: JsonField = JsonMissing.of(), + @JsonProperty("runtime_context") + @ExcludeMissing + runtimeContext: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(code, runtimeContext, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -2216,25 +2488,18 @@ private constructor( * Unlike [type], this method doesn't throw if the JSON field has an unexpected * type. */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Inline = apply { - if (validated) { - return@apply - } - - code() - runtimeContext().validate() - type() - validated = true + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + fun toBuilder() = Builder().from(this) companion object { @@ -2346,25 +2611,60 @@ private constructor( checkRequired("code", code), checkRequired("runtimeContext", runtimeContext), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Inline = apply { + if (validated) { + return@apply + } + + code() + runtimeContext().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (code.asKnown().isPresent) 1 else 0) + + (runtimeContext.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class RuntimeContext - @JsonCreator private constructor( - @JsonProperty("runtime") - @ExcludeMissing - private val runtime: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val runtime: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("runtime") + @ExcludeMissing + runtime: JsonField = JsonMissing.of(), + @JsonProperty("version") + @ExcludeMissing + version: JsonField = JsonMissing.of(), + ) : this(runtime, version, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an * unexpected type or is unexpectedly missing or null (e.g. if the server @@ -2399,21 +2699,15 @@ private constructor( @ExcludeMissing fun _version(): JsonField = version + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): RuntimeContext = apply { - if (validated) { - return@apply - } - - runtime() - version() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2514,10 +2808,41 @@ private constructor( RuntimeContext( checkRequired("runtime", runtime), checkRequired("version", version), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): RuntimeContext = apply { + if (validated) { + return@apply + } + + runtime().validate() + version() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (runtime.asKnown().getOrNull()?.validity() ?: 0) + + (if (version.asKnown().isPresent) 1 else 0) + class Runtime @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -2617,6 +2942,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Runtime = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2736,6 +3089,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2852,6 +3233,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2883,20 +3291,19 @@ private constructor( "Code{data=$data, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Global - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(name, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -2925,21 +3332,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Global = apply { - if (validated) { - return@apply - } - - name() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3032,10 +3433,41 @@ private constructor( Global( checkRequired("name", name), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Global = apply { + if (validated) { + return@apply + } + + name() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -3120,6 +3552,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -3153,35 +3612,32 @@ private constructor( } /** JSON schema for the function's parameters and return type */ - @NoAutoDetect class FunctionSchema - @JsonCreator private constructor( - @JsonProperty("parameters") - @ExcludeMissing - private val parameters: JsonValue = JsonMissing.of(), - @JsonProperty("returns") @ExcludeMissing private val returns: JsonValue = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val parameters: JsonValue, + private val returns: JsonValue, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("parameters") @ExcludeMissing parameters: JsonValue = JsonMissing.of(), + @JsonProperty("returns") @ExcludeMissing returns: JsonValue = JsonMissing.of(), + ) : this(parameters, returns, mutableMapOf()) + @JsonProperty("parameters") @ExcludeMissing fun _parameters(): JsonValue = parameters @JsonProperty("returns") @ExcludeMissing fun _returns(): JsonValue = returns + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): FunctionSchema = apply { - if (validated) { - return@apply - } - - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3234,9 +3690,35 @@ private constructor( * Further updates to this [Builder] will not mutate the returned instance. */ fun build(): FunctionSchema = - FunctionSchema(parameters, returns, additionalProperties.toImmutable()) + FunctionSchema(parameters, returns, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): FunctionSchema = apply { + if (validated) { + return@apply + } + + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = 0 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3357,6 +3839,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): FunctionType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -3370,23 +3879,27 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class Origin - @JsonCreator private constructor( - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("internal") - @ExcludeMissing - private val internal_: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val objectId: JsonField, + private val objectType: JsonField, + private val internal_: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("object_id") + @ExcludeMissing + objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("internal") + @ExcludeMissing + internal_: JsonField = JsonMissing.of(), + ) : this(objectId, objectType, internal_, mutableMapOf()) + /** * Id of the object the function is originating from * @@ -3410,7 +3923,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun internal_(): Optional = Optional.ofNullable(internal_.getNullable("internal")) + fun internal_(): Optional = internal_.getOptional("internal") /** * Returns the raw JSON value of [objectId]. @@ -3435,22 +3948,15 @@ private constructor( */ @JsonProperty("internal") @ExcludeMissing fun _internal_(): JsonField = internal_ + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Origin = apply { - if (validated) { - return@apply - } - - objectId() - objectType() - internal_() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3572,10 +4078,43 @@ private constructor( checkRequired("objectId", objectId), checkRequired("objectType", objectType), internal_, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Origin = apply { + if (validated) { + return@apply + } + + objectId() + objectType().validate() + internal_() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (internal_.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionRetrieveParams.kt index e76a50f4..17d1b879 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> functionId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [FunctionRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var functionId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> functionId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionUpdateParams.kt index be7afe1f..bc199968 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionUpdateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionUpdateParams.kt @@ -9,14 +9,13 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.allMaxBy import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.braintrustdata.api.models.CodeBundle.* @@ -31,6 +30,7 @@ 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.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -130,57 +130,334 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) - override fun _headers(): Headers = additionalHeaders + companion object { - override fun _queryParams(): QueryParams = additionalQueryParams + /** + * Returns a mutable builder for constructing an instance of [FunctionUpdateParams]. + * + * The following fields are required: + * ```java + * .functionId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionUpdateParams]. */ + class Builder internal constructor() { + + private var functionId: 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(functionUpdateParams: FunctionUpdateParams) = apply { + functionId = functionUpdateParams.functionId + body = functionUpdateParams.body.toBuilder() + additionalHeaders = functionUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = functionUpdateParams.additionalQueryParams.toBuilder() + } + + /** Function id */ + fun functionId(functionId: String) = apply { this.functionId = functionId } + + /** + * 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: + * - [description] + * - [functionData] + * - [name] + * - [promptData] + * - [tags] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Textual description of the prompt */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { body.description(description) } + + fun functionData(functionData: FunctionData?) = apply { body.functionData(functionData) } + + /** Alias for calling [Builder.functionData] with `functionData.orElse(null)`. */ + fun functionData(functionData: Optional) = + functionData(functionData.getOrNull()) + + /** + * Sets [Builder.functionData] to an arbitrary JSON value. + * + * You should usually call [Builder.functionData] with a well-typed [FunctionData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun functionData(functionData: JsonField) = apply { + body.functionData(functionData) + } + + /** Alias for calling [functionData] with `FunctionData.ofPrompt(prompt)`. */ + fun functionData(prompt: FunctionData.Prompt) = apply { body.functionData(prompt) } + + /** Alias for calling [functionData] with `FunctionData.ofCode(code)`. */ + fun functionData(code: FunctionData.Code) = apply { body.functionData(code) } + + /** Alias for calling [functionData] with `FunctionData.ofGlobal(global)`. */ + fun functionData(global: FunctionData.Global) = apply { body.functionData(global) } + + /** Name of the prompt */ + fun name(name: String?) = apply { body.name(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 { body.name(name) } + + /** The prompt, model, and its parameters */ + fun promptData(promptData: PromptData?) = apply { body.promptData(promptData) } + + /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ + fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) + + /** + * Sets [Builder.promptData] to an arbitrary JSON value. + * + * You should usually call [Builder.promptData] with a well-typed [PromptData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun promptData(promptData: JsonField) = apply { body.promptData(promptData) } + + /** A list of tags for the prompt */ + fun tags(tags: List?) = apply { body.tags(tags) } + + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) + + /** + * Sets [Builder.tags] to an arbitrary JSON value. + * + * You should usually call [Builder.tags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tags(tags: JsonField>) = apply { body.tags(tags) } + + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { body.addTag(tag) } + + 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 getPathParam(index: Int): String { - return when (index) { + 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 [FunctionUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .functionId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FunctionUpdateParams = + FunctionUpdateParams( + checkRequired("functionId", functionId), + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { 0 -> functionId else -> "" } - } - @NoAutoDetect + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + class Body - @JsonCreator private constructor( - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("function_data") - @ExcludeMissing - private val functionData: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("prompt_data") - @ExcludeMissing - private val promptData: JsonField = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val description: JsonField, + private val functionData: JsonField, + private val name: JsonField, + private val promptData: JsonField, + private val tags: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("function_data") + @ExcludeMissing + functionData: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("prompt_data") + @ExcludeMissing + promptData: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this(description, functionData, name, promptData, tags, mutableMapOf()) + /** * Textual description of the prompt * * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun description(): Optional = description.getOptional("description") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun functionData(): Optional = - Optional.ofNullable(functionData.getNullable("function_data")) + fun functionData(): Optional = functionData.getOptional("function_data") /** * Name of the prompt @@ -188,7 +465,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun name(): Optional = name.getOptional("name") /** * The prompt, model, and its parameters @@ -196,8 +473,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun promptData(): Optional = - Optional.ofNullable(promptData.getNullable("prompt_data")) + fun promptData(): Optional = promptData.getOptional("prompt_data") /** * A list of tags for the prompt @@ -205,7 +481,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [description]. @@ -244,30 +520,21 @@ private constructor( /** * 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 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags - description() - functionData().ifPresent { it.validate() } - name() - promptData().ifPresent { it.validate() } - tags() - validated = true + @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 { @@ -397,326 +664,98 @@ private constructor( * @throws IllegalStateException if the field was previously set to a non-list. */ fun addTag(tag: String) = apply { - tags = - (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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. - */ - fun build(): Body = - Body( - description, - functionData, - name, - promptData, - (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && description == other.description && functionData == other.functionData && name == other.name && promptData == other.promptData && tags == other.tags && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(description, functionData, name, promptData, tags, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{description=$description, functionData=$functionData, name=$name, promptData=$promptData, tags=$tags, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [FunctionUpdateParams]. - * - * The following fields are required: - * ```java - * .functionId() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [FunctionUpdateParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var functionId: 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(functionUpdateParams: FunctionUpdateParams) = apply { - functionId = functionUpdateParams.functionId - body = functionUpdateParams.body.toBuilder() - additionalHeaders = functionUpdateParams.additionalHeaders.toBuilder() - additionalQueryParams = functionUpdateParams.additionalQueryParams.toBuilder() - } - - /** Function id */ - fun functionId(functionId: String) = apply { this.functionId = functionId } - - /** Textual description of the prompt */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun description(description: JsonField) = apply { body.description(description) } - - fun functionData(functionData: FunctionData?) = apply { body.functionData(functionData) } - - /** Alias for calling [Builder.functionData] with `functionData.orElse(null)`. */ - fun functionData(functionData: Optional) = - functionData(functionData.getOrNull()) - - /** - * Sets [Builder.functionData] to an arbitrary JSON value. - * - * You should usually call [Builder.functionData] with a well-typed [FunctionData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun functionData(functionData: JsonField) = apply { - body.functionData(functionData) - } - - /** Alias for calling [functionData] with `FunctionData.ofPrompt(prompt)`. */ - fun functionData(prompt: FunctionData.Prompt) = apply { body.functionData(prompt) } - - /** Alias for calling [functionData] with `FunctionData.ofCode(code)`. */ - fun functionData(code: FunctionData.Code) = apply { body.functionData(code) } - - /** Alias for calling [functionData] with `FunctionData.ofGlobal(global)`. */ - fun functionData(global: FunctionData.Global) = apply { body.functionData(global) } - - /** Name of the prompt */ - fun name(name: String?) = apply { body.name(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 { body.name(name) } - - /** The prompt, model, and its parameters */ - fun promptData(promptData: PromptData?) = apply { body.promptData(promptData) } - - /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ - fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) - - /** - * Sets [Builder.promptData] to an arbitrary JSON value. - * - * You should usually call [Builder.promptData] with a well-typed [PromptData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun promptData(promptData: JsonField) = apply { body.promptData(promptData) } - - /** A list of tags for the prompt */ - fun tags(tags: List?) = apply { body.tags(tags) } - - /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ - fun tags(tags: Optional>) = tags(tags.getOrNull()) - - /** - * Sets [Builder.tags] to an arbitrary JSON value. - * - * You should usually call [Builder.tags] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun tags(tags: JsonField>) = apply { body.tags(tags) } - - /** - * Adds a single [String] to [tags]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addTag(tag: String) = apply { body.addTag(tag) } - - 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) - } + tags = + (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } + } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body( + description, + functionData, + name, + promptData, + (tags ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + private var validated: Boolean = false - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun validate(): Body = apply { + if (validated) { + return@apply } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) + description() + functionData().ifPresent { it.validate() } + name() + promptData().ifPresent { it.validate() } + tags() + validated = true } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + /** + * Returns 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 (description.asKnown().isPresent) 1 else 0) + + (functionData.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (promptData.asKnown().getOrNull()?.validity() ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + return /* spotless:off */ other is Body && description == other.description && functionData == other.functionData && name == other.name && promptData == other.promptData && tags == other.tags && additionalProperties == other.additionalProperties /* spotless:on */ } - /** - * Returns an immutable instance of [FunctionUpdateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .functionId() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): FunctionUpdateParams = - FunctionUpdateParams( - checkRequired("functionId", functionId), - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(description, functionData, name, promptData, tags, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{description=$description, functionData=$functionData, name=$name, promptData=$promptData, tags=$tags, additionalProperties=$additionalProperties}" } @JsonDeserialize(using = FunctionData.Deserializer::class) @@ -749,14 +788,13 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { prompt != null -> visitor.visitPrompt(prompt) code != null -> visitor.visitCode(code) global != null -> visitor.visitGlobal(global) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -783,6 +821,34 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitPrompt(prompt: Prompt) = prompt.validity() + + override fun visitCode(code: Code) = code.validity() + + override fun visitGlobal(global: Global) = global.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -843,20 +909,31 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): FunctionData { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return FunctionData(prompt = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return FunctionData(code = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return FunctionData(global = it, _json = json) - } - - return FunctionData(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionData(prompt = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionData(code = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionData(global = 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 -> FunctionData(_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() + } } } @@ -877,17 +954,17 @@ private constructor( } } - @NoAutoDetect class Prompt - @JsonCreator private constructor( - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of() + ) : this(type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -902,20 +979,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Prompt = apply { - if (validated) { - return@apply - } - - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -990,9 +1062,37 @@ private constructor( * @throws IllegalStateException if any required field is unset. */ fun build(): Prompt = - Prompt(checkRequired("type", type), additionalProperties.toImmutable()) + Prompt(checkRequired("type", type), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Prompt = apply { + if (validated) { + return@apply + } + + type().validate() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1077,6 +1177,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -1108,20 +1235,19 @@ private constructor( "Prompt{type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Code - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -1150,21 +1276,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Code = apply { - if (validated) { - return@apply - } - - data().validate() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1263,10 +1383,41 @@ private constructor( Code( checkRequired("data", data), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Code = apply { + if (validated) { + return@apply + } + + data().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (data.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + @JsonDeserialize(using = Data.Deserializer::class) @JsonSerialize(using = Data.Serializer::class) class Data @@ -1290,13 +1441,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { bundle != null -> visitor.visitBundle(bundle) inline != null -> visitor.visitInline(inline) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1319,6 +1469,32 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitBundle(bundle: Bundle) = bundle.validity() + + override fun visitInline(inline: Inline) = inline.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1374,16 +1550,29 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Data { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Data(bundle = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Data(inline = it, _json = json) - } - - return Data(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Data(bundle = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Data(inline = 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 -> Data(_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() + } } } @@ -1403,30 +1592,43 @@ private constructor( } } - @NoAutoDetect class Bundle - @JsonCreator private constructor( - @JsonProperty("bundle_id") - @ExcludeMissing - private val bundleId: JsonField = JsonMissing.of(), - @JsonProperty("location") - @ExcludeMissing - private val location: JsonField = JsonMissing.of(), - @JsonProperty("runtime_context") - @ExcludeMissing - private val runtimeContext: JsonField = - JsonMissing.of(), - @JsonProperty("preview") - @ExcludeMissing - private val preview: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val bundleId: JsonField, + private val location: JsonField, + private val runtimeContext: JsonField, + private val preview: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("bundle_id") + @ExcludeMissing + bundleId: JsonField = JsonMissing.of(), + @JsonProperty("location") + @ExcludeMissing + location: JsonField = JsonMissing.of(), + @JsonProperty("runtime_context") + @ExcludeMissing + runtimeContext: JsonField = JsonMissing.of(), + @JsonProperty("preview") + @ExcludeMissing + preview: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(bundleId, location, runtimeContext, preview, type, mutableMapOf()) + + fun toCodeBundle(): CodeBundle = + CodeBundle.builder() + .bundleId(bundleId) + .location(location) + .runtimeContext(runtimeContext) + .preview(preview) + .build() + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -1455,8 +1657,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ - fun preview(): Optional = - Optional.ofNullable(preview.getNullable("preview")) + fun preview(): Optional = preview.getOptional("preview") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected @@ -1513,32 +1714,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toCodeBundle(): CodeBundle = - CodeBundle.builder() - .bundleId(bundleId) - .location(location) - .runtimeContext(runtimeContext) - .preview(preview) - .build() - - private var validated: Boolean = false - - fun validate(): Bundle = apply { - if (validated) { - return@apply - } - - bundleId() - location().validate() - runtimeContext().validate() - preview() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1705,10 +1889,47 @@ private constructor( checkRequired("runtimeContext", runtimeContext), preview, checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Bundle = apply { + if (validated) { + return@apply + } + + bundleId() + location().validate() + runtimeContext().validate() + preview() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (bundleId.asKnown().isPresent) 1 else 0) + + (location.asKnown().getOrNull()?.validity() ?: 0) + + (runtimeContext.asKnown().getOrNull()?.validity() ?: 0) + + (if (preview.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1797,6 +2018,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -1828,23 +2077,27 @@ private constructor( "Bundle{bundleId=$bundleId, location=$location, runtimeContext=$runtimeContext, preview=$preview, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Inline - @JsonCreator private constructor( - @JsonProperty("code") - @ExcludeMissing - private val code: JsonField = JsonMissing.of(), - @JsonProperty("runtime_context") - @ExcludeMissing - private val runtimeContext: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val code: JsonField, + private val runtimeContext: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("code") + @ExcludeMissing + code: JsonField = JsonMissing.of(), + @JsonProperty("runtime_context") + @ExcludeMissing + runtimeContext: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(code, runtimeContext, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -1893,22 +2146,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Inline = apply { - if (validated) { - return@apply - } - - code() - runtimeContext().validate() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2021,25 +2267,60 @@ private constructor( checkRequired("code", code), checkRequired("runtimeContext", runtimeContext), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Inline = apply { + if (validated) { + return@apply + } + + code() + runtimeContext().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (code.asKnown().isPresent) 1 else 0) + + (runtimeContext.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class RuntimeContext - @JsonCreator private constructor( - @JsonProperty("runtime") - @ExcludeMissing - private val runtime: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val runtime: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("runtime") + @ExcludeMissing + runtime: JsonField = JsonMissing.of(), + @JsonProperty("version") + @ExcludeMissing + version: JsonField = JsonMissing.of(), + ) : this(runtime, version, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an * unexpected type or is unexpectedly missing or null (e.g. if the server @@ -2074,21 +2355,15 @@ private constructor( @ExcludeMissing fun _version(): JsonField = version + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): RuntimeContext = apply { - if (validated) { - return@apply - } - - runtime() - version() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2189,10 +2464,41 @@ private constructor( RuntimeContext( checkRequired("runtime", runtime), checkRequired("version", version), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): RuntimeContext = apply { + if (validated) { + return@apply + } + + runtime().validate() + version() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (runtime.asKnown().getOrNull()?.validity() ?: 0) + + (if (version.asKnown().isPresent) 1 else 0) + class Runtime @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -2292,6 +2598,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Runtime = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2411,6 +2745,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2527,6 +2889,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2558,20 +2947,19 @@ private constructor( "Code{data=$data, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Global - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(name, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -2600,21 +2988,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Global = apply { - if (validated) { - return@apply - } - - name() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2707,10 +3089,41 @@ private constructor( Global( checkRequired("name", name), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Global = apply { + if (validated) { + return@apply + } + + name() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -2795,6 +3208,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Group.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Group.kt index 4ab379e6..756c44c0 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Group.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Group.kt @@ -6,10 +6,8 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -17,6 +15,7 @@ import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -26,34 +25,54 @@ import kotlin.jvm.optionals.getOrNull * * Groups can consist of individual users, as well as a set of groups they inherit from */ -@NoAutoDetect class Group -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("org_id") @ExcludeMissing private val orgId: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("deleted_at") - @ExcludeMissing - private val deletedAt: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("member_groups") - @ExcludeMissing - private val memberGroups: JsonField> = JsonMissing.of(), - @JsonProperty("member_users") - @ExcludeMissing - private val memberUsers: JsonField> = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val name: JsonField, + private val orgId: JsonField, + private val created: JsonField, + private val deletedAt: JsonField, + private val description: JsonField, + private val memberGroups: JsonField>, + private val memberUsers: JsonField>, + private val userId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("org_id") @ExcludeMissing orgId: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("deleted_at") + @ExcludeMissing + deletedAt: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("member_groups") + @ExcludeMissing + memberGroups: JsonField> = JsonMissing.of(), + @JsonProperty("member_users") + @ExcludeMissing + memberUsers: JsonField> = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this( + id, + name, + orgId, + created, + deletedAt, + description, + memberGroups, + memberUsers, + userId, + mutableMapOf(), + ) + /** * Unique identifier for the group * @@ -86,7 +105,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Date of group deletion, or null if the group is still active @@ -94,8 +113,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun deletedAt(): Optional = - Optional.ofNullable(deletedAt.getNullable("deleted_at")) + fun deletedAt(): Optional = deletedAt.getOptional("deleted_at") /** * Textual description of the group @@ -103,8 +121,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun description(): Optional = description.getOptional("description") /** * Ids of the groups this group inherits from @@ -115,8 +132,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun memberGroups(): Optional> = - Optional.ofNullable(memberGroups.getNullable("member_groups")) + fun memberGroups(): Optional> = memberGroups.getOptional("member_groups") /** * Ids of users which belong to this group @@ -124,8 +140,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun memberUsers(): Optional> = - Optional.ofNullable(memberUsers.getNullable("member_users")) + fun memberUsers(): Optional> = memberUsers.getOptional("member_users") /** * Identifies the user who created the group @@ -133,7 +148,7 @@ private constructor( * @throws BraintrustInvalidDataException 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 [id]. @@ -204,28 +219,15 @@ private constructor( */ @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 = additionalProperties - - private var validated: Boolean = false - - fun validate(): Group = apply { - if (validated) { - return@apply - } - - id() - name() - orgId() - created() - deletedAt() - description() - memberGroups() - memberUsers() - userId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -477,10 +479,54 @@ private constructor( (memberGroups ?: JsonMissing.of()).map { it.toImmutable() }, (memberUsers ?: JsonMissing.of()).map { it.toImmutable() }, userId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Group = apply { + if (validated) { + return@apply + } + + id() + name() + orgId() + created() + deletedAt() + description() + memberGroups() + memberUsers() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (orgId.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (deletedAt.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (memberGroups.asKnown().getOrNull()?.size ?: 0) + + (memberUsers.asKnown().getOrNull()?.size ?: 0) + + (if (userId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupCreateParams.kt index cda2eae4..8843a37b 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupCreateParams.kt @@ -6,19 +6,18 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -120,209 +119,477 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) - override fun _headers(): Headers = additionalHeaders + companion object { - override fun _queryParams(): QueryParams = additionalQueryParams + /** + * Returns a mutable builder for constructing an instance of [GroupCreateParams]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("member_groups") - @ExcludeMissing - private val memberGroups: JsonField> = JsonMissing.of(), - @JsonProperty("member_users") - @ExcludeMissing - private val memberUsers: JsonField> = JsonMissing.of(), - @JsonProperty("org_name") - @ExcludeMissing - private val orgName: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** A builder for [GroupCreateParams]. */ + 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(groupCreateParams: GroupCreateParams) = apply { + body = groupCreateParams.body.toBuilder() + additionalHeaders = groupCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = groupCreateParams.additionalQueryParams.toBuilder() + } /** - * Name of the group + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * 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: + * - [name] + * - [description] + * - [memberGroups] + * - [memberUsers] + * - [orgName] + * - etc. */ - fun name(): String = name.getRequired("name") + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the group */ + fun name(name: String) = apply { body.name(name) } /** - * Textual description of the group + * Sets [Builder.name] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected 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 description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun name(name: JsonField) = apply { body.name(name) } + + /** Textual description of the group */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) /** - * Ids of the groups this group inherits from - * - * An inheriting group has all the users contained in its member groups, as well as all of - * their inherited users + * Sets [Builder.description] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun memberGroups(): Optional> = - Optional.ofNullable(memberGroups.getNullable("member_groups")) + fun description(description: JsonField) = apply { body.description(description) } /** - * Ids of users which belong to this group + * Ids of the groups this group inherits from * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * An inheriting group has all the users contained in its member groups, as well as all of + * their inherited users */ - fun memberUsers(): Optional> = - Optional.ofNullable(memberUsers.getNullable("member_users")) + fun memberGroups(memberGroups: List?) = apply { body.memberGroups(memberGroups) } + + /** Alias for calling [Builder.memberGroups] with `memberGroups.orElse(null)`. */ + fun memberGroups(memberGroups: Optional>) = + memberGroups(memberGroups.getOrNull()) /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the group belongs in. + * Sets [Builder.memberGroups] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.memberGroups] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun orgName(): Optional = Optional.ofNullable(orgName.getNullable("org_name")) + fun memberGroups(memberGroups: JsonField>) = apply { + body.memberGroups(memberGroups) + } /** - * Returns the raw JSON value of [name]. + * Adds a single [String] to [memberGroups]. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun addMemberGroup(memberGroup: String) = apply { body.addMemberGroup(memberGroup) } + + /** Ids of users which belong to this group */ + fun memberUsers(memberUsers: List?) = apply { body.memberUsers(memberUsers) } + + /** Alias for calling [Builder.memberUsers] with `memberUsers.orElse(null)`. */ + fun memberUsers(memberUsers: Optional>) = memberUsers(memberUsers.getOrNull()) /** - * Returns the raw JSON value of [description]. + * Sets [Builder.memberUsers] to an arbitrary JSON value. * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.memberUsers] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description + fun memberUsers(memberUsers: JsonField>) = apply { + body.memberUsers(memberUsers) + } /** - * Returns the raw JSON value of [memberGroups]. + * Adds a single [String] to [memberUsers]. * - * Unlike [memberGroups], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("member_groups") - @ExcludeMissing - fun _memberGroups(): JsonField> = memberGroups + fun addMemberUser(memberUser: String) = apply { body.addMemberUser(memberUser) } /** - * Returns the raw JSON value of [memberUsers]. - * - * Unlike [memberUsers], this method doesn't throw if the JSON field has an unexpected type. + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the group belongs in. */ - @JsonProperty("member_users") - @ExcludeMissing - fun _memberUsers(): JsonField> = memberUsers + fun orgName(orgName: String?) = apply { body.orgName(orgName) } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) /** - * Returns the raw JSON value of [orgName]. + * Sets [Builder.orgName] to an arbitrary JSON value. * - * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.orgName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName + fun orgName(orgName: JsonField) = apply { body.orgName(orgName) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var validated: Boolean = false + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - fun validate(): Body = apply { - if (validated) { - return@apply + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - name() - description() - memberGroups() - memberUsers() - orgName() - validated = true + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - fun toBuilder() = Builder().from(this) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - companion object { + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - private var name: JsonField? = null - private var description: JsonField = JsonMissing.of() - private var memberGroups: JsonField>? = null - private var memberUsers: JsonField>? = null - private var orgName: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - description = body.description - memberGroups = body.memberGroups.map { it.toMutableList() } - memberUsers = body.memberUsers.map { it.toMutableList() } - orgName = body.orgName - additionalProperties = body.additionalProperties.toMutableMap() - } + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Name of the group */ - fun name(name: String) = name(JsonField.of(name)) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * 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 replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** Textual description of the group */ - fun description(description: String?) = description(JsonField.ofNullable(description)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } + 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 [GroupCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): GroupCreateParams = + GroupCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val name: JsonField, + private val description: JsonField, + private val memberGroups: JsonField>, + private val memberUsers: JsonField>, + private val orgName: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("member_groups") + @ExcludeMissing + memberGroups: JsonField> = JsonMissing.of(), + @JsonProperty("member_users") + @ExcludeMissing + memberUsers: JsonField> = JsonMissing.of(), + @JsonProperty("org_name") @ExcludeMissing orgName: JsonField = JsonMissing.of(), + ) : this(name, description, memberGroups, memberUsers, orgName, mutableMapOf()) + + /** + * Name of the group + * + * @throws BraintrustInvalidDataException 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") + + /** + * Textual description of the group + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * Ids of the groups this group inherits from + * + * An inheriting group has all the users contained in its member groups, as well as all of + * their inherited users + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun memberGroups(): Optional> = memberGroups.getOptional("member_groups") + + /** + * Ids of users which belong to this group + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun memberUsers(): Optional> = memberUsers.getOptional("member_users") + + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the group belongs in. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun orgName(): Optional = orgName.getOptional("org_name") + + /** + * 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 [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [memberGroups]. + * + * Unlike [memberGroups], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("member_groups") + @ExcludeMissing + fun _memberGroups(): JsonField> = memberGroups + + /** + * Returns the raw JSON value of [memberUsers]. + * + * Unlike [memberUsers], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("member_users") + @ExcludeMissing + fun _memberUsers(): JsonField> = memberUsers + + /** + * Returns the raw JSON value of [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName + + @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 + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var memberGroups: JsonField>? = null + private var memberUsers: JsonField>? = null + private var orgName: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + description = body.description + memberGroups = body.memberGroups.map { it.toMutableList() } + memberUsers = body.memberUsers.map { it.toMutableList() } + orgName = body.orgName + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the group */ + 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 } + + /** Textual description of the group */ + fun description(description: String?) = description(JsonField.ofNullable(description)) + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + + /** * Ids of the groups this group inherits from * * An inheriting group has all the users contained in its member groups, as well as all @@ -446,291 +713,63 @@ private constructor( (memberGroups ?: JsonMissing.of()).map { it.toImmutable() }, (memberUsers ?: JsonMissing.of()).map { it.toImmutable() }, orgName, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply } - return /* spotless:off */ other is Body && name == other.name && description == other.description && memberGroups == other.memberGroups && memberUsers == other.memberUsers && orgName == other.orgName && additionalProperties == other.additionalProperties /* spotless:on */ + name() + description() + memberGroups() + memberUsers() + orgName() + validated = true } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, description, memberGroups, memberUsers, orgName, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{name=$name, description=$description, memberGroups=$memberGroups, memberUsers=$memberUsers, orgName=$orgName, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } /** - * Returns a mutable builder for constructing an instance of [GroupCreateParams]. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * The following fields are required: - * ```java - * .name() - * ``` + * Used for best match union deserialization. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GroupCreateParams]. */ - @NoAutoDetect - 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(groupCreateParams: GroupCreateParams) = apply { - body = groupCreateParams.body.toBuilder() - additionalHeaders = groupCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = groupCreateParams.additionalQueryParams.toBuilder() - } - - /** Name of the group */ - fun name(name: String) = apply { body.name(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 { body.name(name) } - - /** Textual description of the group */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun description(description: JsonField) = apply { body.description(description) } - - /** - * Ids of the groups this group inherits from - * - * An inheriting group has all the users contained in its member groups, as well as all of - * their inherited users - */ - fun memberGroups(memberGroups: List?) = apply { body.memberGroups(memberGroups) } - - /** Alias for calling [Builder.memberGroups] with `memberGroups.orElse(null)`. */ - fun memberGroups(memberGroups: Optional>) = - memberGroups(memberGroups.getOrNull()) - - /** - * Sets [Builder.memberGroups] to an arbitrary JSON value. - * - * You should usually call [Builder.memberGroups] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun memberGroups(memberGroups: JsonField>) = apply { - body.memberGroups(memberGroups) - } - - /** - * Adds a single [String] to [memberGroups]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addMemberGroup(memberGroup: String) = apply { body.addMemberGroup(memberGroup) } - - /** Ids of users which belong to this group */ - fun memberUsers(memberUsers: List?) = apply { body.memberUsers(memberUsers) } - - /** Alias for calling [Builder.memberUsers] with `memberUsers.orElse(null)`. */ - fun memberUsers(memberUsers: Optional>) = memberUsers(memberUsers.getOrNull()) - - /** - * Sets [Builder.memberUsers] to an arbitrary JSON value. - * - * You should usually call [Builder.memberUsers] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun memberUsers(memberUsers: JsonField>) = apply { - body.memberUsers(memberUsers) - } - - /** - * Adds a single [String] to [memberUsers]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addMemberUser(memberUser: String) = apply { body.addMemberUser(memberUser) } - - /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the group belongs in. - */ - fun orgName(orgName: String?) = apply { body.orgName(orgName) } - - /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ - fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) - - /** - * Sets [Builder.orgName] to an arbitrary JSON value. - * - * You should usually call [Builder.orgName] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun orgName(orgName: JsonField) = apply { body.orgName(orgName) } - - 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) - } + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (memberGroups.asKnown().getOrNull()?.size ?: 0) + + (memberUsers.asKnown().getOrNull()?.size ?: 0) + + (if (orgName.asKnown().isPresent) 1 else 0) - 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) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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) + return /* spotless:off */ other is Body && name == other.name && description == other.description && memberGroups == other.memberGroups && memberUsers == other.memberUsers && orgName == other.orgName && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, description, memberGroups, memberUsers, orgName, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [GroupCreateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): GroupCreateParams = - GroupCreateParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{name=$name, description=$description, memberGroups=$memberGroups, memberUsers=$memberUsers, orgName=$orgName, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupDeleteParams.kt index 07473a4f..95ce78c4 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupDeleteParams.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,26 +23,11 @@ private constructor( /** Group id */ fun groupId(): String = groupId - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> groupId - else -> "" - } - } + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -61,7 +45,6 @@ private constructor( } /** A builder for [GroupDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var groupId: String? = null @@ -221,6 +204,19 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> groupId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListPage.kt index 33debe68..af4e384c 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListPage.kt @@ -2,161 +2,115 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.GroupService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all groups. The groups are sorted by creation date, with the most recently-created - * groups coming first - */ +/** @see [GroupService.list] */ class GroupListPage private constructor( - private val groupsService: GroupService, + private val service: GroupService, private val params: GroupListParams, - private val response: Response, + private val response: GroupListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [GroupListPageResponse], but gracefully handles missing data. + * + * @see [GroupListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is GroupListPage && groupsService == other.groupsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(groupsService, params, response) /* spotless:on */ - - override fun toString() = - "GroupListPage{groupsService=$groupsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - GroupListParams.builder().from(params).endingBefore(objects().first().id()).build() - ) - } else { - Optional.of( - GroupListParams.builder().from(params).startingAfter(objects().last().id()).build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { groupsService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(groupsService: GroupService, params: GroupListParams, response: Response) = - GroupListPage(groupsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): GroupListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): GroupListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [GroupListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [GroupListPage]. */ + class Builder internal constructor() { - companion object { + private var service: GroupService? = null + private var params: GroupListParams? = null + private var response: GroupListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [GroupListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(groupListPage: GroupListPage) = apply { + service = groupListPage.service + params = groupListPage.params + response = groupListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: GroupService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: GroupListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: GroupListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [GroupListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): GroupListPage = + GroupListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: GroupListPage) : Iterable { @@ -177,4 +131,16 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is GroupListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = "GroupListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListPageAsync.kt index 7b8849b1..57388a7d 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListPageAsync.kt @@ -2,163 +2,119 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.GroupServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all groups. The groups are sorted by creation date, with the most recently-created - * groups coming first - */ +/** @see [GroupServiceAsync.list] */ class GroupListPageAsync private constructor( - private val groupsService: GroupServiceAsync, + private val service: GroupServiceAsync, private val params: GroupListParams, - private val response: Response, + private val response: GroupListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [GroupListPageResponse], but gracefully handles missing data. + * + * @see [GroupListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is GroupListPageAsync && groupsService == other.groupsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(groupsService, params, response) /* spotless:on */ - - override fun toString() = - "GroupListPageAsync{groupsService=$groupsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - GroupListParams.builder().from(params).endingBefore(objects().first().id()).build() - ) - } else { - Optional.of( - GroupListParams.builder().from(params).startingAfter(objects().last().id()).build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { groupsService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(groupsService: GroupServiceAsync, params: GroupListParams, response: Response) = - GroupListPageAsync(groupsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): GroupListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): GroupListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [GroupListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [GroupListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: GroupServiceAsync? = null + private var params: GroupListParams? = null + private var response: GroupListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [GroupListPageAsync]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(groupListPageAsync: GroupListPageAsync) = apply { + service = groupListPageAsync.service + params = groupListPageAsync.params + response = groupListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: GroupServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: GroupListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: GroupListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [GroupListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): GroupListPageAsync = + GroupListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: GroupListPageAsync) { @@ -186,4 +142,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is GroupListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "GroupListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListPageResponse.kt new file mode 100644 index 00000000..dafbd5f2 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListPageResponse.kt @@ -0,0 +1,192 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class GroupListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") @ExcludeMissing objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of group objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [GroupListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [GroupListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(groupListPageResponse: GroupListPageResponse) = apply { + objects = groupListPageResponse.objects.map { it.toMutableList() } + additionalProperties = groupListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of group objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [Group] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: Group) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [GroupListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): GroupListPageResponse = + GroupListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): GroupListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is GroupListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "GroupListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListParams.kt index 94cc7e6a..eb8cc72c 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListParams.kt @@ -2,22 +2,10 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -75,31 +63,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - endingBefore?.let { put("ending_before", it) } - groupName?.let { put("group_name", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - orgName?.let { put("org_name", it) } - startingAfter?.let { put("starting_after", it) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -111,7 +74,6 @@ private constructor( } /** A builder for [GroupListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var endingBefore: String? = null @@ -316,17 +278,39 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + endingBefore?.let { put("ending_before", it) } + groupName?.let { put("group_name", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + orgName?.let { put("org_name", it) } + startingAfter?.let { put("starting_after", it) } + putAll(additionalQueryParams) + } + .build() + /** * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -341,15 +325,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -365,7 +346,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -382,51 +362,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupReplaceParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupReplaceParams.kt index b11f2119..281249c7 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupReplaceParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupReplaceParams.kt @@ -6,19 +6,18 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -120,209 +119,477 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) - override fun _headers(): Headers = additionalHeaders + companion object { - override fun _queryParams(): QueryParams = additionalQueryParams + /** + * Returns a mutable builder for constructing an instance of [GroupReplaceParams]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("member_groups") - @ExcludeMissing - private val memberGroups: JsonField> = JsonMissing.of(), - @JsonProperty("member_users") - @ExcludeMissing - private val memberUsers: JsonField> = JsonMissing.of(), - @JsonProperty("org_name") - @ExcludeMissing - private val orgName: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** A builder for [GroupReplaceParams]. */ + 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(groupReplaceParams: GroupReplaceParams) = apply { + body = groupReplaceParams.body.toBuilder() + additionalHeaders = groupReplaceParams.additionalHeaders.toBuilder() + additionalQueryParams = groupReplaceParams.additionalQueryParams.toBuilder() + } /** - * Name of the group + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * 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: + * - [name] + * - [description] + * - [memberGroups] + * - [memberUsers] + * - [orgName] + * - etc. */ - fun name(): String = name.getRequired("name") + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the group */ + fun name(name: String) = apply { body.name(name) } /** - * Textual description of the group + * Sets [Builder.name] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected 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 description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun name(name: JsonField) = apply { body.name(name) } + + /** Textual description of the group */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) /** - * Ids of the groups this group inherits from - * - * An inheriting group has all the users contained in its member groups, as well as all of - * their inherited users + * Sets [Builder.description] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun memberGroups(): Optional> = - Optional.ofNullable(memberGroups.getNullable("member_groups")) + fun description(description: JsonField) = apply { body.description(description) } /** - * Ids of users which belong to this group + * Ids of the groups this group inherits from * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * An inheriting group has all the users contained in its member groups, as well as all of + * their inherited users */ - fun memberUsers(): Optional> = - Optional.ofNullable(memberUsers.getNullable("member_users")) + fun memberGroups(memberGroups: List?) = apply { body.memberGroups(memberGroups) } + + /** Alias for calling [Builder.memberGroups] with `memberGroups.orElse(null)`. */ + fun memberGroups(memberGroups: Optional>) = + memberGroups(memberGroups.getOrNull()) /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the group belongs in. + * Sets [Builder.memberGroups] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.memberGroups] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun orgName(): Optional = Optional.ofNullable(orgName.getNullable("org_name")) + fun memberGroups(memberGroups: JsonField>) = apply { + body.memberGroups(memberGroups) + } /** - * Returns the raw JSON value of [name]. + * Adds a single [String] to [memberGroups]. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun addMemberGroup(memberGroup: String) = apply { body.addMemberGroup(memberGroup) } + + /** Ids of users which belong to this group */ + fun memberUsers(memberUsers: List?) = apply { body.memberUsers(memberUsers) } + + /** Alias for calling [Builder.memberUsers] with `memberUsers.orElse(null)`. */ + fun memberUsers(memberUsers: Optional>) = memberUsers(memberUsers.getOrNull()) /** - * Returns the raw JSON value of [description]. + * Sets [Builder.memberUsers] to an arbitrary JSON value. * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.memberUsers] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description + fun memberUsers(memberUsers: JsonField>) = apply { + body.memberUsers(memberUsers) + } /** - * Returns the raw JSON value of [memberGroups]. + * Adds a single [String] to [memberUsers]. * - * Unlike [memberGroups], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("member_groups") - @ExcludeMissing - fun _memberGroups(): JsonField> = memberGroups + fun addMemberUser(memberUser: String) = apply { body.addMemberUser(memberUser) } /** - * Returns the raw JSON value of [memberUsers]. - * - * Unlike [memberUsers], this method doesn't throw if the JSON field has an unexpected type. + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the group belongs in. */ - @JsonProperty("member_users") - @ExcludeMissing - fun _memberUsers(): JsonField> = memberUsers + fun orgName(orgName: String?) = apply { body.orgName(orgName) } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) /** - * Returns the raw JSON value of [orgName]. + * Sets [Builder.orgName] to an arbitrary JSON value. * - * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.orgName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName + fun orgName(orgName: JsonField) = apply { body.orgName(orgName) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var validated: Boolean = false + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - fun validate(): Body = apply { - if (validated) { - return@apply + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - name() - description() - memberGroups() - memberUsers() - orgName() - validated = true + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - fun toBuilder() = Builder().from(this) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - companion object { + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - private var name: JsonField? = null - private var description: JsonField = JsonMissing.of() - private var memberGroups: JsonField>? = null - private var memberUsers: JsonField>? = null - private var orgName: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - description = body.description - memberGroups = body.memberGroups.map { it.toMutableList() } - memberUsers = body.memberUsers.map { it.toMutableList() } - orgName = body.orgName - additionalProperties = body.additionalProperties.toMutableMap() - } + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Name of the group */ - fun name(name: String) = name(JsonField.of(name)) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * 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 replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** Textual description of the group */ - fun description(description: String?) = description(JsonField.ofNullable(description)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } + 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 [GroupReplaceParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): GroupReplaceParams = + GroupReplaceParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val name: JsonField, + private val description: JsonField, + private val memberGroups: JsonField>, + private val memberUsers: JsonField>, + private val orgName: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("member_groups") + @ExcludeMissing + memberGroups: JsonField> = JsonMissing.of(), + @JsonProperty("member_users") + @ExcludeMissing + memberUsers: JsonField> = JsonMissing.of(), + @JsonProperty("org_name") @ExcludeMissing orgName: JsonField = JsonMissing.of(), + ) : this(name, description, memberGroups, memberUsers, orgName, mutableMapOf()) + + /** + * Name of the group + * + * @throws BraintrustInvalidDataException 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") + + /** + * Textual description of the group + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * Ids of the groups this group inherits from + * + * An inheriting group has all the users contained in its member groups, as well as all of + * their inherited users + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun memberGroups(): Optional> = memberGroups.getOptional("member_groups") + + /** + * Ids of users which belong to this group + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun memberUsers(): Optional> = memberUsers.getOptional("member_users") + + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the group belongs in. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun orgName(): Optional = orgName.getOptional("org_name") + + /** + * 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 [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [memberGroups]. + * + * Unlike [memberGroups], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("member_groups") + @ExcludeMissing + fun _memberGroups(): JsonField> = memberGroups + + /** + * Returns the raw JSON value of [memberUsers]. + * + * Unlike [memberUsers], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("member_users") + @ExcludeMissing + fun _memberUsers(): JsonField> = memberUsers + + /** + * Returns the raw JSON value of [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName + + @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 + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var memberGroups: JsonField>? = null + private var memberUsers: JsonField>? = null + private var orgName: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + description = body.description + memberGroups = body.memberGroups.map { it.toMutableList() } + memberUsers = body.memberUsers.map { it.toMutableList() } + orgName = body.orgName + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the group */ + 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 } + + /** Textual description of the group */ + fun description(description: String?) = description(JsonField.ofNullable(description)) + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + + /** * Ids of the groups this group inherits from * * An inheriting group has all the users contained in its member groups, as well as all @@ -446,291 +713,63 @@ private constructor( (memberGroups ?: JsonMissing.of()).map { it.toImmutable() }, (memberUsers ?: JsonMissing.of()).map { it.toImmutable() }, orgName, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply } - return /* spotless:off */ other is Body && name == other.name && description == other.description && memberGroups == other.memberGroups && memberUsers == other.memberUsers && orgName == other.orgName && additionalProperties == other.additionalProperties /* spotless:on */ + name() + description() + memberGroups() + memberUsers() + orgName() + validated = true } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, description, memberGroups, memberUsers, orgName, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{name=$name, description=$description, memberGroups=$memberGroups, memberUsers=$memberUsers, orgName=$orgName, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } /** - * Returns a mutable builder for constructing an instance of [GroupReplaceParams]. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * The following fields are required: - * ```java - * .name() - * ``` + * Used for best match union deserialization. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GroupReplaceParams]. */ - @NoAutoDetect - 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(groupReplaceParams: GroupReplaceParams) = apply { - body = groupReplaceParams.body.toBuilder() - additionalHeaders = groupReplaceParams.additionalHeaders.toBuilder() - additionalQueryParams = groupReplaceParams.additionalQueryParams.toBuilder() - } - - /** Name of the group */ - fun name(name: String) = apply { body.name(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 { body.name(name) } - - /** Textual description of the group */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun description(description: JsonField) = apply { body.description(description) } - - /** - * Ids of the groups this group inherits from - * - * An inheriting group has all the users contained in its member groups, as well as all of - * their inherited users - */ - fun memberGroups(memberGroups: List?) = apply { body.memberGroups(memberGroups) } - - /** Alias for calling [Builder.memberGroups] with `memberGroups.orElse(null)`. */ - fun memberGroups(memberGroups: Optional>) = - memberGroups(memberGroups.getOrNull()) - - /** - * Sets [Builder.memberGroups] to an arbitrary JSON value. - * - * You should usually call [Builder.memberGroups] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun memberGroups(memberGroups: JsonField>) = apply { - body.memberGroups(memberGroups) - } - - /** - * Adds a single [String] to [memberGroups]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addMemberGroup(memberGroup: String) = apply { body.addMemberGroup(memberGroup) } - - /** Ids of users which belong to this group */ - fun memberUsers(memberUsers: List?) = apply { body.memberUsers(memberUsers) } - - /** Alias for calling [Builder.memberUsers] with `memberUsers.orElse(null)`. */ - fun memberUsers(memberUsers: Optional>) = memberUsers(memberUsers.getOrNull()) - - /** - * Sets [Builder.memberUsers] to an arbitrary JSON value. - * - * You should usually call [Builder.memberUsers] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun memberUsers(memberUsers: JsonField>) = apply { - body.memberUsers(memberUsers) - } - - /** - * Adds a single [String] to [memberUsers]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addMemberUser(memberUser: String) = apply { body.addMemberUser(memberUser) } - - /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the group belongs in. - */ - fun orgName(orgName: String?) = apply { body.orgName(orgName) } - - /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ - fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) - - /** - * Sets [Builder.orgName] to an arbitrary JSON value. - * - * You should usually call [Builder.orgName] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun orgName(orgName: JsonField) = apply { body.orgName(orgName) } - - 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) - } + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (memberGroups.asKnown().getOrNull()?.size ?: 0) + + (memberUsers.asKnown().getOrNull()?.size ?: 0) + + (if (orgName.asKnown().isPresent) 1 else 0) - 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) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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) + return /* spotless:off */ other is Body && name == other.name && description == other.description && memberGroups == other.memberGroups && memberUsers == other.memberUsers && orgName == other.orgName && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, description, memberGroups, memberUsers, orgName, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [GroupReplaceParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): GroupReplaceParams = - GroupReplaceParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{name=$name, description=$description, memberGroups=$memberGroups, memberUsers=$memberUsers, orgName=$orgName, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupRetrieveParams.kt index 1105cf21..0134decd 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> groupId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [GroupRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var groupId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> groupId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupUpdateParams.kt index 8009fc68..1eef9986 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupUpdateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupUpdateParams.kt @@ -6,19 +6,18 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -137,191 +136,523 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) - override fun _headers(): Headers = additionalHeaders + companion object { - override fun _queryParams(): QueryParams = additionalQueryParams + /** + * Returns a mutable builder for constructing an instance of [GroupUpdateParams]. + * + * The following fields are required: + * ```java + * .groupId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - fun getPathParam(index: Int): String { - return when (index) { - 0 -> groupId - else -> "" + /** A builder for [GroupUpdateParams]. */ + class Builder internal constructor() { + + private var groupId: 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(groupUpdateParams: GroupUpdateParams) = apply { + groupId = groupUpdateParams.groupId + body = groupUpdateParams.body.toBuilder() + additionalHeaders = groupUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = groupUpdateParams.additionalQueryParams.toBuilder() } - } - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("add_member_groups") - @ExcludeMissing - private val addMemberGroups: JsonField> = JsonMissing.of(), - @JsonProperty("add_member_users") - @ExcludeMissing - private val addMemberUsers: JsonField> = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("remove_member_groups") - @ExcludeMissing - private val removeMemberGroups: JsonField> = JsonMissing.of(), - @JsonProperty("remove_member_users") - @ExcludeMissing - private val removeMemberUsers: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** Group id */ + fun groupId(groupId: String) = apply { this.groupId = groupId } /** - * A list of group IDs to add to the group's inheriting-from set + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [addMemberGroups] + * - [addMemberUsers] + * - [description] + * - [name] + * - [removeMemberGroups] + * - etc. */ - fun addMemberGroups(): Optional> = - Optional.ofNullable(addMemberGroups.getNullable("add_member_groups")) + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** A list of group IDs to add to the group's inheriting-from set */ + fun addMemberGroups(addMemberGroups: List?) = apply { + body.addMemberGroups(addMemberGroups) + } + + /** Alias for calling [Builder.addMemberGroups] with `addMemberGroups.orElse(null)`. */ + fun addMemberGroups(addMemberGroups: Optional>) = + addMemberGroups(addMemberGroups.getOrNull()) /** - * A list of user IDs to add to the group + * Sets [Builder.addMemberGroups] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.addMemberGroups] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun addMemberUsers(): Optional> = - Optional.ofNullable(addMemberUsers.getNullable("add_member_users")) + fun addMemberGroups(addMemberGroups: JsonField>) = apply { + body.addMemberGroups(addMemberGroups) + } /** - * Textual description of the group + * Adds a single [String] to [addMemberGroups]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * @throws IllegalStateException if the field was previously set to a non-list. */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun addAddMemberGroup(addMemberGroup: String) = apply { + body.addAddMemberGroup(addMemberGroup) + } + + /** A list of user IDs to add to the group */ + fun addMemberUsers(addMemberUsers: List?) = apply { + body.addMemberUsers(addMemberUsers) + } + + /** Alias for calling [Builder.addMemberUsers] with `addMemberUsers.orElse(null)`. */ + fun addMemberUsers(addMemberUsers: Optional>) = + addMemberUsers(addMemberUsers.getOrNull()) /** - * Name of the group + * Sets [Builder.addMemberUsers] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.addMemberUsers] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun addMemberUsers(addMemberUsers: JsonField>) = apply { + body.addMemberUsers(addMemberUsers) + } /** - * A list of group IDs to remove from the group's inheriting-from set + * Adds a single [String] to [addMemberUsers]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * @throws IllegalStateException if the field was previously set to a non-list. */ - fun removeMemberGroups(): Optional> = - Optional.ofNullable(removeMemberGroups.getNullable("remove_member_groups")) + fun addAddMemberUser(addMemberUser: String) = apply { body.addAddMemberUser(addMemberUser) } + + /** Textual description of the group */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) /** - * A list of user IDs to remove from the group + * Sets [Builder.description] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun removeMemberUsers(): Optional> = - Optional.ofNullable(removeMemberUsers.getNullable("remove_member_users")) + fun description(description: JsonField) = apply { body.description(description) } + + /** Name of the group */ + fun name(name: String?) = apply { body.name(name) } + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) /** - * Returns the raw JSON value of [addMemberGroups]. + * Sets [Builder.name] to an arbitrary JSON value. * - * Unlike [addMemberGroups], this method doesn't throw if the JSON field has an unexpected - * type. + * 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. */ - @JsonProperty("add_member_groups") - @ExcludeMissing - fun _addMemberGroups(): JsonField> = addMemberGroups + fun name(name: JsonField) = apply { body.name(name) } + + /** A list of group IDs to remove from the group's inheriting-from set */ + fun removeMemberGroups(removeMemberGroups: List?) = apply { + body.removeMemberGroups(removeMemberGroups) + } /** - * Returns the raw JSON value of [addMemberUsers]. - * - * Unlike [addMemberUsers], this method doesn't throw if the JSON field has an unexpected - * type. + * Alias for calling [Builder.removeMemberGroups] with `removeMemberGroups.orElse(null)`. */ - @JsonProperty("add_member_users") - @ExcludeMissing - fun _addMemberUsers(): JsonField> = addMemberUsers + fun removeMemberGroups(removeMemberGroups: Optional>) = + removeMemberGroups(removeMemberGroups.getOrNull()) /** - * Returns the raw JSON value of [description]. + * Sets [Builder.removeMemberGroups] to an arbitrary JSON value. * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.removeMemberGroups] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description + fun removeMemberGroups(removeMemberGroups: JsonField>) = apply { + body.removeMemberGroups(removeMemberGroups) + } /** - * Returns the raw JSON value of [name]. + * Adds a single [String] to [removeMemberGroups]. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun addRemoveMemberGroup(removeMemberGroup: String) = apply { + body.addRemoveMemberGroup(removeMemberGroup) + } + + /** A list of user IDs to remove from the group */ + fun removeMemberUsers(removeMemberUsers: List?) = apply { + body.removeMemberUsers(removeMemberUsers) + } + + /** Alias for calling [Builder.removeMemberUsers] with `removeMemberUsers.orElse(null)`. */ + fun removeMemberUsers(removeMemberUsers: Optional>) = + removeMemberUsers(removeMemberUsers.getOrNull()) /** - * Returns the raw JSON value of [removeMemberGroups]. + * Sets [Builder.removeMemberUsers] to an arbitrary JSON value. * - * Unlike [removeMemberGroups], this method doesn't throw if the JSON field has an - * unexpected type. + * You should usually call [Builder.removeMemberUsers] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. */ - @JsonProperty("remove_member_groups") - @ExcludeMissing - fun _removeMemberGroups(): JsonField> = removeMemberGroups + fun removeMemberUsers(removeMemberUsers: JsonField>) = apply { + body.removeMemberUsers(removeMemberUsers) + } /** - * Returns the raw JSON value of [removeMemberUsers]. + * Adds a single [String] to [removeMemberUsers]. * - * Unlike [removeMemberUsers], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("remove_member_users") - @ExcludeMissing - fun _removeMemberUsers(): JsonField> = removeMemberUsers + fun addRemoveMemberUser(removeMemberUser: String) = apply { + body.addRemoveMemberUser(removeMemberUser) + } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var validated: Boolean = false + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - fun validate(): Body = apply { - if (validated) { - return@apply + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - addMemberGroups() - addMemberUsers() - description() - name() - removeMemberGroups() - removeMemberUsers() - validated = true + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - fun toBuilder() = Builder().from(this) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - companion object { + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Returns a mutable builder for constructing an instance of [Body]. */ - @JvmStatic fun builder() = Builder() + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - private var addMemberGroups: JsonField>? = null - private var addMemberUsers: JsonField>? = null - private var description: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var removeMemberGroups: JsonField>? = null - private var removeMemberUsers: JsonField>? = null + 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 [GroupUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .groupId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): GroupUpdateParams = + GroupUpdateParams( + checkRequired("groupId", groupId), + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> groupId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val addMemberGroups: JsonField>, + private val addMemberUsers: JsonField>, + private val description: JsonField, + private val name: JsonField, + private val removeMemberGroups: JsonField>, + private val removeMemberUsers: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("add_member_groups") + @ExcludeMissing + addMemberGroups: JsonField> = JsonMissing.of(), + @JsonProperty("add_member_users") + @ExcludeMissing + addMemberUsers: JsonField> = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("remove_member_groups") + @ExcludeMissing + removeMemberGroups: JsonField> = JsonMissing.of(), + @JsonProperty("remove_member_users") + @ExcludeMissing + removeMemberUsers: JsonField> = JsonMissing.of(), + ) : this( + addMemberGroups, + addMemberUsers, + description, + name, + removeMemberGroups, + removeMemberUsers, + mutableMapOf(), + ) + + /** + * A list of group IDs to add to the group's inheriting-from set + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun addMemberGroups(): Optional> = + addMemberGroups.getOptional("add_member_groups") + + /** + * A list of user IDs to add to the group + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun addMemberUsers(): Optional> = + addMemberUsers.getOptional("add_member_users") + + /** + * Textual description of the group + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * Name of the group + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * A list of group IDs to remove from the group's inheriting-from set + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun removeMemberGroups(): Optional> = + removeMemberGroups.getOptional("remove_member_groups") + + /** + * A list of user IDs to remove from the group + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun removeMemberUsers(): Optional> = + removeMemberUsers.getOptional("remove_member_users") + + /** + * Returns the raw JSON value of [addMemberGroups]. + * + * Unlike [addMemberGroups], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("add_member_groups") + @ExcludeMissing + fun _addMemberGroups(): JsonField> = addMemberGroups + + /** + * Returns the raw JSON value of [addMemberUsers]. + * + * Unlike [addMemberUsers], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("add_member_users") + @ExcludeMissing + fun _addMemberUsers(): JsonField> = addMemberUsers + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [removeMemberGroups]. + * + * Unlike [removeMemberGroups], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("remove_member_groups") + @ExcludeMissing + fun _removeMemberGroups(): JsonField> = removeMemberGroups + + /** + * Returns the raw JSON value of [removeMemberUsers]. + * + * Unlike [removeMemberUsers], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("remove_member_users") + @ExcludeMissing + fun _removeMemberUsers(): JsonField> = removeMemberUsers + + @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]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var addMemberGroups: JsonField>? = null + private var addMemberUsers: JsonField>? = null + private var description: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var removeMemberGroups: JsonField>? = null + private var removeMemberUsers: JsonField>? = null private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic @@ -528,344 +859,65 @@ private constructor( name, (removeMemberGroups ?: JsonMissing.of()).map { it.toImmutable() }, (removeMemberUsers ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply } - return /* spotless:off */ other is Body && addMemberGroups == other.addMemberGroups && addMemberUsers == other.addMemberUsers && description == other.description && name == other.name && removeMemberGroups == other.removeMemberGroups && removeMemberUsers == other.removeMemberUsers && additionalProperties == other.additionalProperties /* spotless:on */ + addMemberGroups() + addMemberUsers() + description() + name() + removeMemberGroups() + removeMemberUsers() + validated = true } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(addMemberGroups, addMemberUsers, description, name, removeMemberGroups, removeMemberUsers, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{addMemberGroups=$addMemberGroups, addMemberUsers=$addMemberUsers, description=$description, name=$name, removeMemberGroups=$removeMemberGroups, removeMemberUsers=$removeMemberUsers, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } /** - * Returns a mutable builder for constructing an instance of [GroupUpdateParams]. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * The following fields are required: - * ```java - * .groupId() - * ``` + * Used for best match union deserialization. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GroupUpdateParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var groupId: 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(groupUpdateParams: GroupUpdateParams) = apply { - groupId = groupUpdateParams.groupId - body = groupUpdateParams.body.toBuilder() - additionalHeaders = groupUpdateParams.additionalHeaders.toBuilder() - additionalQueryParams = groupUpdateParams.additionalQueryParams.toBuilder() - } - - /** Group id */ - fun groupId(groupId: String) = apply { this.groupId = groupId } - - /** A list of group IDs to add to the group's inheriting-from set */ - fun addMemberGroups(addMemberGroups: List?) = apply { - body.addMemberGroups(addMemberGroups) - } - - /** Alias for calling [Builder.addMemberGroups] with `addMemberGroups.orElse(null)`. */ - fun addMemberGroups(addMemberGroups: Optional>) = - addMemberGroups(addMemberGroups.getOrNull()) - - /** - * Sets [Builder.addMemberGroups] to an arbitrary JSON value. - * - * You should usually call [Builder.addMemberGroups] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun addMemberGroups(addMemberGroups: JsonField>) = apply { - body.addMemberGroups(addMemberGroups) - } - - /** - * Adds a single [String] to [addMemberGroups]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addAddMemberGroup(addMemberGroup: String) = apply { - body.addAddMemberGroup(addMemberGroup) - } - - /** A list of user IDs to add to the group */ - fun addMemberUsers(addMemberUsers: List?) = apply { - body.addMemberUsers(addMemberUsers) - } - - /** Alias for calling [Builder.addMemberUsers] with `addMemberUsers.orElse(null)`. */ - fun addMemberUsers(addMemberUsers: Optional>) = - addMemberUsers(addMemberUsers.getOrNull()) - - /** - * Sets [Builder.addMemberUsers] to an arbitrary JSON value. - * - * You should usually call [Builder.addMemberUsers] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun addMemberUsers(addMemberUsers: JsonField>) = apply { - body.addMemberUsers(addMemberUsers) - } - - /** - * Adds a single [String] to [addMemberUsers]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addAddMemberUser(addMemberUser: String) = apply { body.addAddMemberUser(addMemberUser) } - - /** Textual description of the group */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun description(description: JsonField) = apply { body.description(description) } - - /** Name of the group */ - fun name(name: String?) = apply { body.name(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 { body.name(name) } - - /** A list of group IDs to remove from the group's inheriting-from set */ - fun removeMemberGroups(removeMemberGroups: List?) = apply { - body.removeMemberGroups(removeMemberGroups) - } - - /** - * Alias for calling [Builder.removeMemberGroups] with `removeMemberGroups.orElse(null)`. - */ - fun removeMemberGroups(removeMemberGroups: Optional>) = - removeMemberGroups(removeMemberGroups.getOrNull()) - - /** - * Sets [Builder.removeMemberGroups] to an arbitrary JSON value. - * - * You should usually call [Builder.removeMemberGroups] with a well-typed `List` - * value instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun removeMemberGroups(removeMemberGroups: JsonField>) = apply { - body.removeMemberGroups(removeMemberGroups) - } - - /** - * Adds a single [String] to [removeMemberGroups]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addRemoveMemberGroup(removeMemberGroup: String) = apply { - body.addRemoveMemberGroup(removeMemberGroup) - } - - /** A list of user IDs to remove from the group */ - fun removeMemberUsers(removeMemberUsers: List?) = apply { - body.removeMemberUsers(removeMemberUsers) - } - - /** Alias for calling [Builder.removeMemberUsers] with `removeMemberUsers.orElse(null)`. */ - fun removeMemberUsers(removeMemberUsers: Optional>) = - removeMemberUsers(removeMemberUsers.getOrNull()) - - /** - * Sets [Builder.removeMemberUsers] to an arbitrary JSON value. - * - * You should usually call [Builder.removeMemberUsers] with a well-typed `List` - * value instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun removeMemberUsers(removeMemberUsers: JsonField>) = apply { - body.removeMemberUsers(removeMemberUsers) - } - - /** - * Adds a single [String] to [removeMemberUsers]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addRemoveMemberUser(removeMemberUser: String) = apply { - body.addRemoveMemberUser(removeMemberUser) - } - - 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) } + internal fun validity(): Int = + (addMemberGroups.asKnown().getOrNull()?.size ?: 0) + + (addMemberUsers.asKnown().getOrNull()?.size ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (removeMemberGroups.asKnown().getOrNull()?.size ?: 0) + + (removeMemberUsers.asKnown().getOrNull()?.size ?: 0) - 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) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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) + return /* spotless:off */ other is Body && addMemberGroups == other.addMemberGroups && addMemberUsers == other.addMemberUsers && description == other.description && name == other.name && removeMemberGroups == other.removeMemberGroups && removeMemberUsers == other.removeMemberUsers && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(addMemberGroups, addMemberUsers, description, name, removeMemberGroups, removeMemberUsers, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [GroupUpdateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .groupId() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): GroupUpdateParams = - GroupUpdateParams( - checkRequired("groupId", groupId), - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{addMemberGroups=$addMemberGroups, addMemberUsers=$addMemberUsers, description=$description, name=$name, removeMemberGroups=$removeMemberGroups, removeMemberUsers=$removeMemberUsers, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertDatasetEvent.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertDatasetEvent.kt index abeb2f43..f19ac1e2 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertDatasetEvent.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertDatasetEvent.kt @@ -6,9 +6,7 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -16,54 +14,77 @@ import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull /** A dataset event */ -@NoAutoDetect class InsertDatasetEvent -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("_is_merge") - @ExcludeMissing - private val _isMerge: JsonField = JsonMissing.of(), - @JsonProperty("_merge_paths") - @ExcludeMissing - private val _mergePaths: JsonField>> = JsonMissing.of(), - @JsonProperty("_object_delete") - @ExcludeMissing - private val _objectDelete: JsonField = JsonMissing.of(), - @JsonProperty("_parent_id") - @ExcludeMissing - private val _parentId: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("expected") @ExcludeMissing private val expected: JsonValue = JsonMissing.of(), - @JsonProperty("input") @ExcludeMissing private val input: JsonValue = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("origin") - @ExcludeMissing - private val origin: JsonField = JsonMissing.of(), - @JsonProperty("root_span_id") - @ExcludeMissing - private val rootSpanId: JsonField = JsonMissing.of(), - @JsonProperty("span_id") - @ExcludeMissing - private val spanId: JsonField = JsonMissing.of(), - @JsonProperty("span_parents") - @ExcludeMissing - private val spanParents: JsonField> = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val _isMerge: JsonField, + private val _mergePaths: JsonField>>, + private val _objectDelete: JsonField, + private val _parentId: JsonField, + private val created: JsonField, + private val expected: JsonValue, + private val input: JsonValue, + private val metadata: JsonField, + private val origin: JsonField, + private val rootSpanId: JsonField, + private val spanId: JsonField, + private val spanParents: JsonField>, + private val tags: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("_is_merge") @ExcludeMissing _isMerge: JsonField = JsonMissing.of(), + @JsonProperty("_merge_paths") + @ExcludeMissing + _mergePaths: JsonField>> = JsonMissing.of(), + @JsonProperty("_object_delete") + @ExcludeMissing + _objectDelete: JsonField = JsonMissing.of(), + @JsonProperty("_parent_id") @ExcludeMissing _parentId: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("expected") @ExcludeMissing expected: JsonValue = JsonMissing.of(), + @JsonProperty("input") @ExcludeMissing input: JsonValue = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("origin") + @ExcludeMissing + origin: JsonField = JsonMissing.of(), + @JsonProperty("root_span_id") + @ExcludeMissing + rootSpanId: JsonField = JsonMissing.of(), + @JsonProperty("span_id") @ExcludeMissing spanId: JsonField = JsonMissing.of(), + @JsonProperty("span_parents") + @ExcludeMissing + spanParents: JsonField> = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this( + id, + _isMerge, + _mergePaths, + _objectDelete, + _parentId, + created, + expected, + input, + metadata, + origin, + rootSpanId, + spanId, + spanParents, + tags, + mutableMapOf(), + ) + /** * A unique identifier for the dataset event. If you don't provide one, BrainTrust will generate * one for you @@ -71,7 +92,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + fun id(): Optional = id.getOptional("id") /** * The `_is_merge` field controls how the row is merged with any existing row with the same id @@ -88,7 +109,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun _isMerge(): Optional = Optional.ofNullable(_isMerge.getNullable("_is_merge")) + fun _isMerge(): Optional = _isMerge.getOptional("_is_merge") /** * The `_merge_paths` field allows controlling the depth of the merge, when `_is_merge=true`. @@ -106,8 +127,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun _mergePaths(): Optional>> = - Optional.ofNullable(_mergePaths.getNullable("_merge_paths")) + fun _mergePaths(): Optional>> = _mergePaths.getOptional("_merge_paths") /** * Pass `_object_delete=true` to mark the dataset event deleted. Deleted events will not show up @@ -116,8 +136,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun _objectDelete(): Optional = - Optional.ofNullable(_objectDelete.getNullable("_object_delete")) + fun _objectDelete(): Optional = _objectDelete.getOptional("_object_delete") /** * DEPRECATED: The `_parent_id` field is deprecated and should not be used. Support for @@ -140,7 +159,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun _parentId(): Optional = Optional.ofNullable(_parentId.getNullable("_parent_id")) + fun _parentId(): Optional = _parentId.getOptional("_parent_id") /** * The timestamp the dataset event was created @@ -148,7 +167,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * The output of your application, including post-processing (an arbitrary, JSON serializable @@ -169,7 +188,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** * Indicates the event was copied from another object. @@ -177,7 +196,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun origin(): Optional = Optional.ofNullable(origin.getNullable("origin")) + fun origin(): Optional = origin.getOptional("origin") /** * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now @@ -198,7 +217,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun rootSpanId(): Optional = Optional.ofNullable(rootSpanId.getNullable("root_span_id")) + fun rootSpanId(): Optional = rootSpanId.getOptional("root_span_id") /** * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now @@ -219,7 +238,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spanId(): Optional = Optional.ofNullable(spanId.getNullable("span_id")) + fun spanId(): Optional = spanId.getOptional("span_id") /** * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now @@ -240,8 +259,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spanParents(): Optional> = - Optional.ofNullable(spanParents.getNullable("span_parents")) + fun spanParents(): Optional> = spanParents.getOptional("span_parents") /** * A list of tags to log @@ -249,7 +267,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [id]. @@ -341,31 +359,15 @@ private constructor( */ @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): InsertDatasetEvent = apply { - if (validated) { - return@apply - } - - id() - _isMerge() - _mergePaths() - _objectDelete() - _parentId() - created() - metadata().ifPresent { it.validate() } - origin().ifPresent { it.validate() } - rootSpanId() - spanId() - spanParents() - tags() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -801,10 +803,60 @@ private constructor( spanId, (spanParents ?: JsonMissing.of()).map { it.toImmutable() }, (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): InsertDatasetEvent = apply { + if (validated) { + return@apply + } + + id() + _isMerge() + _mergePaths() + _objectDelete() + _parentId() + created() + metadata().ifPresent { it.validate() } + origin().ifPresent { it.validate() } + rootSpanId() + spanId() + spanParents() + tags() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (_isMerge.asKnown().isPresent) 1 else 0) + + (_mergePaths.asKnown().getOrNull()?.sumOf { it.size.toInt() } ?: 0) + + (if (_objectDelete.asKnown().isPresent) 1 else 0) + + (if (_parentId.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (origin.asKnown().getOrNull()?.validity() ?: 0) + + (if (rootSpanId.asKnown().isPresent) 1 else 0) + + (if (spanId.asKnown().isPresent) 1 else 0) + + (spanParents.asKnown().getOrNull()?.size ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + /** * A dictionary with additional data about the test example, model outputs, or just about * anything else that's relevant, that you can use to help find and analyze examples later. For @@ -812,24 +864,24 @@ private constructor( * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys * must be strings */ - @NoAutoDetect class Metadata - @JsonCreator private constructor( - @JsonProperty("model") - @ExcludeMissing - private val model: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val model: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of() + ) : this(model, mutableMapOf()) + /** * The model used for this example * * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [model]. @@ -838,20 +890,15 @@ private constructor( */ @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - model() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -912,9 +959,36 @@ private constructor( * * Further updates to this [Builder] will not mutate the returned instance. */ - fun build(): Metadata = Metadata(model, additionalProperties.toImmutable()) + fun build(): Metadata = Metadata(model, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + model() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertEventsResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertEventsResponse.kt index 8d756030..becc87ae 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertEventsResponse.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertEventsResponse.kt @@ -6,28 +6,29 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 kotlin.jvm.optionals.getOrNull -@NoAutoDetect class InsertEventsResponse -@JsonCreator private constructor( - @JsonProperty("row_ids") - @ExcludeMissing - private val rowIds: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val rowIds: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("row_ids") @ExcludeMissing rowIds: JsonField> = JsonMissing.of() + ) : this(rowIds, mutableMapOf()) + /** * The ids of all rows that were inserted, aligning one-to-one with the rows provided as input * @@ -43,20 +44,15 @@ private constructor( */ @JsonProperty("row_ids") @ExcludeMissing fun _rowIds(): JsonField> = rowIds + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): InsertEventsResponse = apply { - if (validated) { - return@apply - } - - rowIds() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -148,10 +144,36 @@ private constructor( fun build(): InsertEventsResponse = InsertEventsResponse( checkRequired("rowIds", rowIds).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): InsertEventsResponse = apply { + if (validated) { + return@apply + } + + rowIds() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (rowIds.asKnown().getOrNull()?.size ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertExperimentEvent.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertExperimentEvent.kt index 946c2f68..d45b6b9a 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertExperimentEvent.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertExperimentEvent.kt @@ -6,9 +6,7 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -16,68 +14,97 @@ import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull /** An experiment event */ -@NoAutoDetect class InsertExperimentEvent -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("_is_merge") - @ExcludeMissing - private val _isMerge: JsonField = JsonMissing.of(), - @JsonProperty("_merge_paths") - @ExcludeMissing - private val _mergePaths: JsonField>> = JsonMissing.of(), - @JsonProperty("_object_delete") - @ExcludeMissing - private val _objectDelete: JsonField = JsonMissing.of(), - @JsonProperty("_parent_id") - @ExcludeMissing - private val _parentId: JsonField = JsonMissing.of(), - @JsonProperty("context") - @ExcludeMissing - private val context: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("error") @ExcludeMissing private val error: JsonValue = JsonMissing.of(), - @JsonProperty("expected") @ExcludeMissing private val expected: JsonValue = JsonMissing.of(), - @JsonProperty("input") @ExcludeMissing private val input: JsonValue = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("metrics") - @ExcludeMissing - private val metrics: JsonField = JsonMissing.of(), - @JsonProperty("origin") - @ExcludeMissing - private val origin: JsonField = JsonMissing.of(), - @JsonProperty("output") @ExcludeMissing private val output: JsonValue = JsonMissing.of(), - @JsonProperty("root_span_id") - @ExcludeMissing - private val rootSpanId: JsonField = JsonMissing.of(), - @JsonProperty("scores") - @ExcludeMissing - private val scores: JsonField = JsonMissing.of(), - @JsonProperty("span_attributes") - @ExcludeMissing - private val spanAttributes: JsonField = JsonMissing.of(), - @JsonProperty("span_id") - @ExcludeMissing - private val spanId: JsonField = JsonMissing.of(), - @JsonProperty("span_parents") - @ExcludeMissing - private val spanParents: JsonField> = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val _isMerge: JsonField, + private val _mergePaths: JsonField>>, + private val _objectDelete: JsonField, + private val _parentId: JsonField, + private val context: JsonField, + private val created: JsonField, + private val error: JsonValue, + private val expected: JsonValue, + private val input: JsonValue, + private val metadata: JsonField, + private val metrics: JsonField, + private val origin: JsonField, + private val output: JsonValue, + private val rootSpanId: JsonField, + private val scores: JsonField, + private val spanAttributes: JsonField, + private val spanId: JsonField, + private val spanParents: JsonField>, + private val tags: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("_is_merge") @ExcludeMissing _isMerge: JsonField = JsonMissing.of(), + @JsonProperty("_merge_paths") + @ExcludeMissing + _mergePaths: JsonField>> = JsonMissing.of(), + @JsonProperty("_object_delete") + @ExcludeMissing + _objectDelete: JsonField = JsonMissing.of(), + @JsonProperty("_parent_id") @ExcludeMissing _parentId: JsonField = JsonMissing.of(), + @JsonProperty("context") @ExcludeMissing context: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("error") @ExcludeMissing error: JsonValue = JsonMissing.of(), + @JsonProperty("expected") @ExcludeMissing expected: JsonValue = JsonMissing.of(), + @JsonProperty("input") @ExcludeMissing input: JsonValue = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("metrics") @ExcludeMissing metrics: JsonField = JsonMissing.of(), + @JsonProperty("origin") + @ExcludeMissing + origin: JsonField = JsonMissing.of(), + @JsonProperty("output") @ExcludeMissing output: JsonValue = JsonMissing.of(), + @JsonProperty("root_span_id") + @ExcludeMissing + rootSpanId: JsonField = JsonMissing.of(), + @JsonProperty("scores") @ExcludeMissing scores: JsonField = JsonMissing.of(), + @JsonProperty("span_attributes") + @ExcludeMissing + spanAttributes: JsonField = JsonMissing.of(), + @JsonProperty("span_id") @ExcludeMissing spanId: JsonField = JsonMissing.of(), + @JsonProperty("span_parents") + @ExcludeMissing + spanParents: JsonField> = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this( + id, + _isMerge, + _mergePaths, + _objectDelete, + _parentId, + context, + created, + error, + expected, + input, + metadata, + metrics, + origin, + output, + rootSpanId, + scores, + spanAttributes, + spanId, + spanParents, + tags, + mutableMapOf(), + ) + /** * A unique identifier for the experiment event. If you don't provide one, BrainTrust will * generate one for you @@ -85,7 +112,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + fun id(): Optional = id.getOptional("id") /** * The `_is_merge` field controls how the row is merged with any existing row with the same id @@ -102,7 +129,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun _isMerge(): Optional = Optional.ofNullable(_isMerge.getNullable("_is_merge")) + fun _isMerge(): Optional = _isMerge.getOptional("_is_merge") /** * The `_merge_paths` field allows controlling the depth of the merge, when `_is_merge=true`. @@ -120,8 +147,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun _mergePaths(): Optional>> = - Optional.ofNullable(_mergePaths.getNullable("_merge_paths")) + fun _mergePaths(): Optional>> = _mergePaths.getOptional("_merge_paths") /** * Pass `_object_delete=true` to mark the experiment event deleted. Deleted events will not show @@ -130,8 +156,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun _objectDelete(): Optional = - Optional.ofNullable(_objectDelete.getNullable("_object_delete")) + fun _objectDelete(): Optional = _objectDelete.getOptional("_object_delete") /** * DEPRECATED: The `_parent_id` field is deprecated and should not be used. Support for @@ -154,7 +179,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun _parentId(): Optional = Optional.ofNullable(_parentId.getNullable("_parent_id")) + fun _parentId(): Optional = _parentId.getOptional("_parent_id") /** * Context is additional information about the code that produced the experiment event. It is @@ -164,7 +189,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun context(): Optional = Optional.ofNullable(context.getNullable("context")) + fun context(): Optional = context.getOptional("context") /** * The timestamp the experiment event was created @@ -172,7 +197,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** The error that occurred, if any. */ @JsonProperty("error") @ExcludeMissing fun _error(): JsonValue = error @@ -205,7 +230,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** * Metrics are numerical measurements tracking the execution of the code that produced the @@ -215,7 +240,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metrics(): Optional = Optional.ofNullable(metrics.getNullable("metrics")) + fun metrics(): Optional = metrics.getOptional("metrics") /** * Indicates the event was copied from another object. @@ -223,7 +248,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun origin(): Optional = Optional.ofNullable(origin.getNullable("origin")) + fun origin(): Optional = origin.getOptional("origin") /** * The output of your application, including post-processing (an arbitrary, JSON serializable @@ -253,7 +278,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun rootSpanId(): Optional = Optional.ofNullable(rootSpanId.getNullable("root_span_id")) + fun rootSpanId(): Optional = rootSpanId.getOptional("root_span_id") /** * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a variety @@ -267,7 +292,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun scores(): Optional = Optional.ofNullable(scores.getNullable("scores")) + fun scores(): Optional = scores.getOptional("scores") /** * Human-identifying attributes of the span, such as name, type, etc. @@ -275,8 +300,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spanAttributes(): Optional = - Optional.ofNullable(spanAttributes.getNullable("span_attributes")) + fun spanAttributes(): Optional = spanAttributes.getOptional("span_attributes") /** * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now @@ -297,7 +321,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spanId(): Optional = Optional.ofNullable(spanId.getNullable("span_id")) + fun spanId(): Optional = spanId.getOptional("span_id") /** * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now @@ -318,8 +342,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spanParents(): Optional> = - Optional.ofNullable(spanParents.getNullable("span_parents")) + fun spanParents(): Optional> = spanParents.getOptional("span_parents") /** * A list of tags to log @@ -327,7 +350,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [id]. @@ -449,35 +472,15 @@ private constructor( */ @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): InsertExperimentEvent = apply { - if (validated) { - return@apply - } - - id() - _isMerge() - _mergePaths() - _objectDelete() - _parentId() - context().ifPresent { it.validate() } - created() - metadata().ifPresent { it.validate() } - metrics().ifPresent { it.validate() } - origin().ifPresent { it.validate() } - rootSpanId() - scores().ifPresent { it.validate() } - spanAttributes().ifPresent { it.validate() } - spanId() - spanParents() - tags() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1027,40 +1030,101 @@ private constructor( spanId, (spanParents ?: JsonMissing.of()).map { it.toImmutable() }, (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): InsertExperimentEvent = apply { + if (validated) { + return@apply + } + + id() + _isMerge() + _mergePaths() + _objectDelete() + _parentId() + context().ifPresent { it.validate() } + created() + metadata().ifPresent { it.validate() } + metrics().ifPresent { it.validate() } + origin().ifPresent { it.validate() } + rootSpanId() + scores().ifPresent { it.validate() } + spanAttributes().ifPresent { it.validate() } + spanId() + spanParents() + tags() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (_isMerge.asKnown().isPresent) 1 else 0) + + (_mergePaths.asKnown().getOrNull()?.sumOf { it.size.toInt() } ?: 0) + + (if (_objectDelete.asKnown().isPresent) 1 else 0) + + (if (_parentId.asKnown().isPresent) 1 else 0) + + (context.asKnown().getOrNull()?.validity() ?: 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (metrics.asKnown().getOrNull()?.validity() ?: 0) + + (origin.asKnown().getOrNull()?.validity() ?: 0) + + (if (rootSpanId.asKnown().isPresent) 1 else 0) + + (scores.asKnown().getOrNull()?.validity() ?: 0) + + (spanAttributes.asKnown().getOrNull()?.validity() ?: 0) + + (if (spanId.asKnown().isPresent) 1 else 0) + + (spanParents.asKnown().getOrNull()?.size ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + /** * Context is additional information about the code that produced the experiment event. It is * essentially the textual counterpart to `metrics`. Use the `caller_*` attributes to track the * location in code which produced the experiment event */ - @NoAutoDetect class Context - @JsonCreator private constructor( - @JsonProperty("caller_filename") - @ExcludeMissing - private val callerFilename: JsonField = JsonMissing.of(), - @JsonProperty("caller_functionname") - @ExcludeMissing - private val callerFunctionname: JsonField = JsonMissing.of(), - @JsonProperty("caller_lineno") - @ExcludeMissing - private val callerLineno: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val callerFilename: JsonField, + private val callerFunctionname: JsonField, + private val callerLineno: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("caller_filename") + @ExcludeMissing + callerFilename: JsonField = JsonMissing.of(), + @JsonProperty("caller_functionname") + @ExcludeMissing + callerFunctionname: JsonField = JsonMissing.of(), + @JsonProperty("caller_lineno") + @ExcludeMissing + callerLineno: JsonField = JsonMissing.of(), + ) : this(callerFilename, callerFunctionname, callerLineno, mutableMapOf()) + /** * Name of the file in code where the experiment event was created * * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun callerFilename(): Optional = - Optional.ofNullable(callerFilename.getNullable("caller_filename")) + fun callerFilename(): Optional = callerFilename.getOptional("caller_filename") /** * The function in code which created the experiment event @@ -1069,7 +1133,7 @@ private constructor( * the server responded with an unexpected value). */ fun callerFunctionname(): Optional = - Optional.ofNullable(callerFunctionname.getNullable("caller_functionname")) + callerFunctionname.getOptional("caller_functionname") /** * Line of code where the experiment event was created @@ -1077,8 +1141,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun callerLineno(): Optional = - Optional.ofNullable(callerLineno.getNullable("caller_lineno")) + fun callerLineno(): Optional = callerLineno.getOptional("caller_lineno") /** * Returns the raw JSON value of [callerFilename]. @@ -1110,22 +1173,15 @@ private constructor( @ExcludeMissing fun _callerLineno(): JsonField = callerLineno + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Context = apply { - if (validated) { - return@apply - } - - callerFilename() - callerFunctionname() - callerLineno() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1245,10 +1301,43 @@ private constructor( callerFilename, callerFunctionname, callerLineno, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Context = apply { + if (validated) { + return@apply + } + + callerFilename() + callerFunctionname() + callerLineno() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (callerFilename.asKnown().isPresent) 1 else 0) + + (if (callerFunctionname.asKnown().isPresent) 1 else 0) + + (if (callerLineno.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1274,24 +1363,24 @@ private constructor( * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys * must be strings */ - @NoAutoDetect class Metadata - @JsonCreator private constructor( - @JsonProperty("model") - @ExcludeMissing - private val model: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val model: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of() + ) : this(model, mutableMapOf()) + /** * The model used for this example * * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [model]. @@ -1300,20 +1389,15 @@ private constructor( */ @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - model() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1374,9 +1458,36 @@ private constructor( * * Further updates to this [Builder] will not mutate the returned instance. */ - fun build(): Metadata = Metadata(model, additionalProperties.toImmutable()) + fun build(): Metadata = Metadata(model, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + model() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1400,36 +1511,51 @@ private constructor( * experiment event. Use "start" and "end" to track the time span over which the experiment * event was produced */ - @NoAutoDetect class Metrics - @JsonCreator private constructor( - @JsonProperty("caller_filename") - @ExcludeMissing - private val callerFilename: JsonValue = JsonMissing.of(), - @JsonProperty("caller_functionname") - @ExcludeMissing - private val callerFunctionname: JsonValue = JsonMissing.of(), - @JsonProperty("caller_lineno") - @ExcludeMissing - private val callerLineno: JsonValue = JsonMissing.of(), - @JsonProperty("completion_tokens") - @ExcludeMissing - private val completionTokens: JsonField = JsonMissing.of(), - @JsonProperty("end") @ExcludeMissing private val end: JsonField = JsonMissing.of(), - @JsonProperty("prompt_tokens") - @ExcludeMissing - private val promptTokens: JsonField = JsonMissing.of(), - @JsonProperty("start") - @ExcludeMissing - private val start: JsonField = JsonMissing.of(), - @JsonProperty("tokens") - @ExcludeMissing - private val tokens: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val callerFilename: JsonValue, + private val callerFunctionname: JsonValue, + private val callerLineno: JsonValue, + private val completionTokens: JsonField, + private val end: JsonField, + private val promptTokens: JsonField, + private val start: JsonField, + private val tokens: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("caller_filename") + @ExcludeMissing + callerFilename: JsonValue = JsonMissing.of(), + @JsonProperty("caller_functionname") + @ExcludeMissing + callerFunctionname: JsonValue = JsonMissing.of(), + @JsonProperty("caller_lineno") + @ExcludeMissing + callerLineno: JsonValue = JsonMissing.of(), + @JsonProperty("completion_tokens") + @ExcludeMissing + completionTokens: JsonField = JsonMissing.of(), + @JsonProperty("end") @ExcludeMissing end: JsonField = JsonMissing.of(), + @JsonProperty("prompt_tokens") + @ExcludeMissing + promptTokens: JsonField = JsonMissing.of(), + @JsonProperty("start") @ExcludeMissing start: JsonField = JsonMissing.of(), + @JsonProperty("tokens") @ExcludeMissing tokens: JsonField = JsonMissing.of(), + ) : this( + callerFilename, + callerFunctionname, + callerLineno, + completionTokens, + end, + promptTokens, + start, + tokens, + mutableMapOf(), + ) + /** This metric is deprecated */ @JsonProperty("caller_filename") @ExcludeMissing @@ -1450,8 +1576,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * A unix timestamp recording when the section of code which produced the experiment event @@ -1460,7 +1585,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun end(): Optional = Optional.ofNullable(end.getNullable("end")) + fun end(): Optional = end.getOptional("end") /** * The number of tokens in the prompt used to generate the experiment event (only set if @@ -1469,8 +1594,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * A unix timestamp recording when the section of code which produced the experiment event @@ -1479,7 +1603,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun start(): Optional = Optional.ofNullable(start.getNullable("start")) + fun start(): Optional = start.getOptional("start") /** * The total number of tokens in the input and output of the experiment event. @@ -1487,7 +1611,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun tokens(): Optional = Optional.ofNullable(tokens.getNullable("tokens")) + fun tokens(): Optional = tokens.getOptional("tokens") /** * Returns the raw JSON value of [completionTokens]. @@ -1530,24 +1654,15 @@ private constructor( */ @JsonProperty("tokens") @ExcludeMissing fun _tokens(): JsonField = tokens + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metrics = apply { - if (validated) { - return@apply - } - - completionTokens() - end() - promptTokens() - start() - tokens() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1761,10 +1876,47 @@ private constructor( promptTokens, start, tokens, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Metrics = apply { + if (validated) { + return@apply + } + + completionTokens() + end() + promptTokens() + start() + tokens() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (completionTokens.asKnown().isPresent) 1 else 0) + + (if (end.asKnown().isPresent) 1 else 0) + + (if (promptTokens.asKnown().isPresent) 1 else 0) + + (if (start.asKnown().isPresent) 1 else 0) + + (if (tokens.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1792,28 +1944,17 @@ private constructor( * whether the summarization was covering similar concepts or not. You can use these scores to * help you sort, filter, and compare experiments */ - @NoAutoDetect class Scores @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Scores = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -1859,6 +2000,34 @@ private constructor( fun build(): Scores = Scores(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Scores = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertProjectLogsEvent.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertProjectLogsEvent.kt index af3e8ffb..1062598d 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertProjectLogsEvent.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertProjectLogsEvent.kt @@ -6,9 +6,7 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -16,68 +14,97 @@ import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull /** A project logs event */ -@NoAutoDetect class InsertProjectLogsEvent -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("_is_merge") - @ExcludeMissing - private val _isMerge: JsonField = JsonMissing.of(), - @JsonProperty("_merge_paths") - @ExcludeMissing - private val _mergePaths: JsonField>> = JsonMissing.of(), - @JsonProperty("_object_delete") - @ExcludeMissing - private val _objectDelete: JsonField = JsonMissing.of(), - @JsonProperty("_parent_id") - @ExcludeMissing - private val _parentId: JsonField = JsonMissing.of(), - @JsonProperty("context") - @ExcludeMissing - private val context: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("error") @ExcludeMissing private val error: JsonValue = JsonMissing.of(), - @JsonProperty("expected") @ExcludeMissing private val expected: JsonValue = JsonMissing.of(), - @JsonProperty("input") @ExcludeMissing private val input: JsonValue = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("metrics") - @ExcludeMissing - private val metrics: JsonField = JsonMissing.of(), - @JsonProperty("origin") - @ExcludeMissing - private val origin: JsonField = JsonMissing.of(), - @JsonProperty("output") @ExcludeMissing private val output: JsonValue = JsonMissing.of(), - @JsonProperty("root_span_id") - @ExcludeMissing - private val rootSpanId: JsonField = JsonMissing.of(), - @JsonProperty("scores") - @ExcludeMissing - private val scores: JsonField = JsonMissing.of(), - @JsonProperty("span_attributes") - @ExcludeMissing - private val spanAttributes: JsonField = JsonMissing.of(), - @JsonProperty("span_id") - @ExcludeMissing - private val spanId: JsonField = JsonMissing.of(), - @JsonProperty("span_parents") - @ExcludeMissing - private val spanParents: JsonField> = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val _isMerge: JsonField, + private val _mergePaths: JsonField>>, + private val _objectDelete: JsonField, + private val _parentId: JsonField, + private val context: JsonField, + private val created: JsonField, + private val error: JsonValue, + private val expected: JsonValue, + private val input: JsonValue, + private val metadata: JsonField, + private val metrics: JsonField, + private val origin: JsonField, + private val output: JsonValue, + private val rootSpanId: JsonField, + private val scores: JsonField, + private val spanAttributes: JsonField, + private val spanId: JsonField, + private val spanParents: JsonField>, + private val tags: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("_is_merge") @ExcludeMissing _isMerge: JsonField = JsonMissing.of(), + @JsonProperty("_merge_paths") + @ExcludeMissing + _mergePaths: JsonField>> = JsonMissing.of(), + @JsonProperty("_object_delete") + @ExcludeMissing + _objectDelete: JsonField = JsonMissing.of(), + @JsonProperty("_parent_id") @ExcludeMissing _parentId: JsonField = JsonMissing.of(), + @JsonProperty("context") @ExcludeMissing context: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("error") @ExcludeMissing error: JsonValue = JsonMissing.of(), + @JsonProperty("expected") @ExcludeMissing expected: JsonValue = JsonMissing.of(), + @JsonProperty("input") @ExcludeMissing input: JsonValue = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("metrics") @ExcludeMissing metrics: JsonField = JsonMissing.of(), + @JsonProperty("origin") + @ExcludeMissing + origin: JsonField = JsonMissing.of(), + @JsonProperty("output") @ExcludeMissing output: JsonValue = JsonMissing.of(), + @JsonProperty("root_span_id") + @ExcludeMissing + rootSpanId: JsonField = JsonMissing.of(), + @JsonProperty("scores") @ExcludeMissing scores: JsonField = JsonMissing.of(), + @JsonProperty("span_attributes") + @ExcludeMissing + spanAttributes: JsonField = JsonMissing.of(), + @JsonProperty("span_id") @ExcludeMissing spanId: JsonField = JsonMissing.of(), + @JsonProperty("span_parents") + @ExcludeMissing + spanParents: JsonField> = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this( + id, + _isMerge, + _mergePaths, + _objectDelete, + _parentId, + context, + created, + error, + expected, + input, + metadata, + metrics, + origin, + output, + rootSpanId, + scores, + spanAttributes, + spanId, + spanParents, + tags, + mutableMapOf(), + ) + /** * A unique identifier for the project logs event. If you don't provide one, BrainTrust will * generate one for you @@ -85,7 +112,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + fun id(): Optional = id.getOptional("id") /** * The `_is_merge` field controls how the row is merged with any existing row with the same id @@ -102,7 +129,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun _isMerge(): Optional = Optional.ofNullable(_isMerge.getNullable("_is_merge")) + fun _isMerge(): Optional = _isMerge.getOptional("_is_merge") /** * The `_merge_paths` field allows controlling the depth of the merge, when `_is_merge=true`. @@ -120,8 +147,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun _mergePaths(): Optional>> = - Optional.ofNullable(_mergePaths.getNullable("_merge_paths")) + fun _mergePaths(): Optional>> = _mergePaths.getOptional("_merge_paths") /** * Pass `_object_delete=true` to mark the project logs event deleted. Deleted events will not @@ -130,8 +156,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun _objectDelete(): Optional = - Optional.ofNullable(_objectDelete.getNullable("_object_delete")) + fun _objectDelete(): Optional = _objectDelete.getOptional("_object_delete") /** * DEPRECATED: The `_parent_id` field is deprecated and should not be used. Support for @@ -154,7 +179,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun _parentId(): Optional = Optional.ofNullable(_parentId.getNullable("_parent_id")) + fun _parentId(): Optional = _parentId.getOptional("_parent_id") /** * Context is additional information about the code that produced the project logs event. It is @@ -164,7 +189,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun context(): Optional = Optional.ofNullable(context.getNullable("context")) + fun context(): Optional = context.getOptional("context") /** * The timestamp the project logs event was created @@ -172,7 +197,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** The error that occurred, if any. */ @JsonProperty("error") @ExcludeMissing fun _error(): JsonValue = error @@ -200,7 +225,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** * Metrics are numerical measurements tracking the execution of the code that produced the @@ -210,7 +235,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metrics(): Optional = Optional.ofNullable(metrics.getNullable("metrics")) + fun metrics(): Optional = metrics.getOptional("metrics") /** * Indicates the event was copied from another object. @@ -218,7 +243,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun origin(): Optional = Optional.ofNullable(origin.getNullable("origin")) + fun origin(): Optional = origin.getOptional("origin") /** * The output of your application, including post-processing (an arbitrary, JSON serializable @@ -248,7 +273,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun rootSpanId(): Optional = Optional.ofNullable(rootSpanId.getNullable("root_span_id")) + fun rootSpanId(): Optional = rootSpanId.getOptional("root_span_id") /** * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a variety @@ -262,7 +287,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun scores(): Optional = Optional.ofNullable(scores.getNullable("scores")) + fun scores(): Optional = scores.getOptional("scores") /** * Human-identifying attributes of the span, such as name, type, etc. @@ -270,8 +295,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spanAttributes(): Optional = - Optional.ofNullable(spanAttributes.getNullable("span_attributes")) + fun spanAttributes(): Optional = spanAttributes.getOptional("span_attributes") /** * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now @@ -292,7 +316,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spanId(): Optional = Optional.ofNullable(spanId.getNullable("span_id")) + fun spanId(): Optional = spanId.getOptional("span_id") /** * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now @@ -313,8 +337,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spanParents(): Optional> = - Optional.ofNullable(spanParents.getNullable("span_parents")) + fun spanParents(): Optional> = spanParents.getOptional("span_parents") /** * A list of tags to log @@ -322,7 +345,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [id]. @@ -444,35 +467,15 @@ private constructor( */ @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): InsertProjectLogsEvent = apply { - if (validated) { - return@apply - } - - id() - _isMerge() - _mergePaths() - _objectDelete() - _parentId() - context().ifPresent { it.validate() } - created() - metadata().ifPresent { it.validate() } - metrics().ifPresent { it.validate() } - origin().ifPresent { it.validate() } - rootSpanId() - scores().ifPresent { it.validate() } - spanAttributes().ifPresent { it.validate() } - spanId() - spanParents() - tags() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1019,40 +1022,101 @@ private constructor( spanId, (spanParents ?: JsonMissing.of()).map { it.toImmutable() }, (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): InsertProjectLogsEvent = apply { + if (validated) { + return@apply + } + + id() + _isMerge() + _mergePaths() + _objectDelete() + _parentId() + context().ifPresent { it.validate() } + created() + metadata().ifPresent { it.validate() } + metrics().ifPresent { it.validate() } + origin().ifPresent { it.validate() } + rootSpanId() + scores().ifPresent { it.validate() } + spanAttributes().ifPresent { it.validate() } + spanId() + spanParents() + tags() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (_isMerge.asKnown().isPresent) 1 else 0) + + (_mergePaths.asKnown().getOrNull()?.sumOf { it.size.toInt() } ?: 0) + + (if (_objectDelete.asKnown().isPresent) 1 else 0) + + (if (_parentId.asKnown().isPresent) 1 else 0) + + (context.asKnown().getOrNull()?.validity() ?: 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (metrics.asKnown().getOrNull()?.validity() ?: 0) + + (origin.asKnown().getOrNull()?.validity() ?: 0) + + (if (rootSpanId.asKnown().isPresent) 1 else 0) + + (scores.asKnown().getOrNull()?.validity() ?: 0) + + (spanAttributes.asKnown().getOrNull()?.validity() ?: 0) + + (if (spanId.asKnown().isPresent) 1 else 0) + + (spanParents.asKnown().getOrNull()?.size ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + /** * Context is additional information about the code that produced the project logs event. It is * essentially the textual counterpart to `metrics`. Use the `caller_*` attributes to track the * location in code which produced the project logs event */ - @NoAutoDetect class Context - @JsonCreator private constructor( - @JsonProperty("caller_filename") - @ExcludeMissing - private val callerFilename: JsonField = JsonMissing.of(), - @JsonProperty("caller_functionname") - @ExcludeMissing - private val callerFunctionname: JsonField = JsonMissing.of(), - @JsonProperty("caller_lineno") - @ExcludeMissing - private val callerLineno: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val callerFilename: JsonField, + private val callerFunctionname: JsonField, + private val callerLineno: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("caller_filename") + @ExcludeMissing + callerFilename: JsonField = JsonMissing.of(), + @JsonProperty("caller_functionname") + @ExcludeMissing + callerFunctionname: JsonField = JsonMissing.of(), + @JsonProperty("caller_lineno") + @ExcludeMissing + callerLineno: JsonField = JsonMissing.of(), + ) : this(callerFilename, callerFunctionname, callerLineno, mutableMapOf()) + /** * Name of the file in code where the project logs event was created * * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun callerFilename(): Optional = - Optional.ofNullable(callerFilename.getNullable("caller_filename")) + fun callerFilename(): Optional = callerFilename.getOptional("caller_filename") /** * The function in code which created the project logs event @@ -1061,7 +1125,7 @@ private constructor( * the server responded with an unexpected value). */ fun callerFunctionname(): Optional = - Optional.ofNullable(callerFunctionname.getNullable("caller_functionname")) + callerFunctionname.getOptional("caller_functionname") /** * Line of code where the project logs event was created @@ -1069,8 +1133,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun callerLineno(): Optional = - Optional.ofNullable(callerLineno.getNullable("caller_lineno")) + fun callerLineno(): Optional = callerLineno.getOptional("caller_lineno") /** * Returns the raw JSON value of [callerFilename]. @@ -1102,22 +1165,15 @@ private constructor( @ExcludeMissing fun _callerLineno(): JsonField = callerLineno + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Context = apply { - if (validated) { - return@apply - } - - callerFilename() - callerFunctionname() - callerLineno() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1237,10 +1293,43 @@ private constructor( callerFilename, callerFunctionname, callerLineno, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Context = apply { + if (validated) { + return@apply + } + + callerFilename() + callerFunctionname() + callerLineno() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (callerFilename.asKnown().isPresent) 1 else 0) + + (if (callerFunctionname.asKnown().isPresent) 1 else 0) + + (if (callerLineno.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1266,24 +1355,24 @@ private constructor( * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys * must be strings */ - @NoAutoDetect class Metadata - @JsonCreator private constructor( - @JsonProperty("model") - @ExcludeMissing - private val model: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val model: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of() + ) : this(model, mutableMapOf()) + /** * The model used for this example * * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [model]. @@ -1292,20 +1381,15 @@ private constructor( */ @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - model() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1366,9 +1450,36 @@ private constructor( * * Further updates to this [Builder] will not mutate the returned instance. */ - fun build(): Metadata = Metadata(model, additionalProperties.toImmutable()) + fun build(): Metadata = Metadata(model, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + model() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1392,36 +1503,51 @@ private constructor( * project logs event. Use "start" and "end" to track the time span over which the project logs * event was produced */ - @NoAutoDetect class Metrics - @JsonCreator private constructor( - @JsonProperty("caller_filename") - @ExcludeMissing - private val callerFilename: JsonValue = JsonMissing.of(), - @JsonProperty("caller_functionname") - @ExcludeMissing - private val callerFunctionname: JsonValue = JsonMissing.of(), - @JsonProperty("caller_lineno") - @ExcludeMissing - private val callerLineno: JsonValue = JsonMissing.of(), - @JsonProperty("completion_tokens") - @ExcludeMissing - private val completionTokens: JsonField = JsonMissing.of(), - @JsonProperty("end") @ExcludeMissing private val end: JsonField = JsonMissing.of(), - @JsonProperty("prompt_tokens") - @ExcludeMissing - private val promptTokens: JsonField = JsonMissing.of(), - @JsonProperty("start") - @ExcludeMissing - private val start: JsonField = JsonMissing.of(), - @JsonProperty("tokens") - @ExcludeMissing - private val tokens: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val callerFilename: JsonValue, + private val callerFunctionname: JsonValue, + private val callerLineno: JsonValue, + private val completionTokens: JsonField, + private val end: JsonField, + private val promptTokens: JsonField, + private val start: JsonField, + private val tokens: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("caller_filename") + @ExcludeMissing + callerFilename: JsonValue = JsonMissing.of(), + @JsonProperty("caller_functionname") + @ExcludeMissing + callerFunctionname: JsonValue = JsonMissing.of(), + @JsonProperty("caller_lineno") + @ExcludeMissing + callerLineno: JsonValue = JsonMissing.of(), + @JsonProperty("completion_tokens") + @ExcludeMissing + completionTokens: JsonField = JsonMissing.of(), + @JsonProperty("end") @ExcludeMissing end: JsonField = JsonMissing.of(), + @JsonProperty("prompt_tokens") + @ExcludeMissing + promptTokens: JsonField = JsonMissing.of(), + @JsonProperty("start") @ExcludeMissing start: JsonField = JsonMissing.of(), + @JsonProperty("tokens") @ExcludeMissing tokens: JsonField = JsonMissing.of(), + ) : this( + callerFilename, + callerFunctionname, + callerLineno, + completionTokens, + end, + promptTokens, + start, + tokens, + mutableMapOf(), + ) + /** This metric is deprecated */ @JsonProperty("caller_filename") @ExcludeMissing @@ -1442,8 +1568,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * A unix timestamp recording when the section of code which produced the project logs event @@ -1452,7 +1577,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun end(): Optional = Optional.ofNullable(end.getNullable("end")) + fun end(): Optional = end.getOptional("end") /** * The number of tokens in the prompt used to generate the project logs event (only set if @@ -1461,8 +1586,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * A unix timestamp recording when the section of code which produced the project logs event @@ -1471,7 +1595,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun start(): Optional = Optional.ofNullable(start.getNullable("start")) + fun start(): Optional = start.getOptional("start") /** * The total number of tokens in the input and output of the project logs event. @@ -1479,7 +1603,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun tokens(): Optional = Optional.ofNullable(tokens.getNullable("tokens")) + fun tokens(): Optional = tokens.getOptional("tokens") /** * Returns the raw JSON value of [completionTokens]. @@ -1522,24 +1646,15 @@ private constructor( */ @JsonProperty("tokens") @ExcludeMissing fun _tokens(): JsonField = tokens + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metrics = apply { - if (validated) { - return@apply - } - - completionTokens() - end() - promptTokens() - start() - tokens() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1753,10 +1868,47 @@ private constructor( promptTokens, start, tokens, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Metrics = apply { + if (validated) { + return@apply + } + + completionTokens() + end() + promptTokens() + start() + tokens() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (completionTokens.asKnown().isPresent) 1 else 0) + + (if (end.asKnown().isPresent) 1 else 0) + + (if (promptTokens.asKnown().isPresent) 1 else 0) + + (if (start.asKnown().isPresent) 1 else 0) + + (if (tokens.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1784,28 +1936,17 @@ private constructor( * whether the summarization was covering similar concepts or not. You can use these scores to * help you sort, filter, and compare logs. */ - @NoAutoDetect class Scores @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Scores = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -1851,6 +1992,34 @@ private constructor( fun build(): Scores = Scores(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Scores = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/MetricSummary.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/MetricSummary.kt index a6233247..04a8b3fe 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/MetricSummary.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/MetricSummary.kt @@ -6,38 +6,42 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 /** Summary of a metric's performance */ -@NoAutoDetect class MetricSummary -@JsonCreator private constructor( - @JsonProperty("improvements") - @ExcludeMissing - private val improvements: JsonField = JsonMissing.of(), - @JsonProperty("metric") - @ExcludeMissing - private val metric: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("regressions") - @ExcludeMissing - private val regressions: JsonField = JsonMissing.of(), - @JsonProperty("unit") @ExcludeMissing private val unit: JsonField = JsonMissing.of(), - @JsonProperty("diff") @ExcludeMissing private val diff: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val improvements: JsonField, + private val metric: JsonField, + private val name: JsonField, + private val regressions: JsonField, + private val unit: JsonField, + private val diff: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("improvements") + @ExcludeMissing + improvements: JsonField = JsonMissing.of(), + @JsonProperty("metric") @ExcludeMissing metric: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("regressions") + @ExcludeMissing + regressions: JsonField = JsonMissing.of(), + @JsonProperty("unit") @ExcludeMissing unit: JsonField = JsonMissing.of(), + @JsonProperty("diff") @ExcludeMissing diff: JsonField = JsonMissing.of(), + ) : this(improvements, metric, name, regressions, unit, diff, mutableMapOf()) + /** * Number of improvements in the metric * @@ -84,7 +88,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun diff(): Optional = Optional.ofNullable(diff.getNullable("diff")) + fun diff(): Optional = diff.getOptional("diff") /** * Returns the raw JSON value of [improvements]. @@ -130,25 +134,15 @@ private constructor( */ @JsonProperty("diff") @ExcludeMissing fun _diff(): JsonField = diff + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): MetricSummary = apply { - if (validated) { - return@apply - } - - improvements() - metric() - name() - regressions() - unit() - diff() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -302,10 +296,48 @@ private constructor( checkRequired("regressions", regressions), checkRequired("unit", unit), diff, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): MetricSummary = apply { + if (validated) { + return@apply + } + + improvements() + metric() + name() + regressions() + unit() + diff() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (improvements.asKnown().isPresent) 1 else 0) + + (if (metric.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (regressions.asKnown().isPresent) 1 else 0) + + (if (unit.asKnown().isPresent) 1 else 0) + + (if (diff.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ObjectReference.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ObjectReference.kt index 381f219f..b55336ff 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ObjectReference.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ObjectReference.kt @@ -7,40 +7,39 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 /** Indicates the event was copied from another object. */ -@NoAutoDetect class ObjectReference -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("_xact_id") - @ExcludeMissing - private val _xactId: JsonField = JsonMissing.of(), - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val _xactId: JsonField, + private val objectId: JsonField, + private val objectType: JsonField, + private val created: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("_xact_id") @ExcludeMissing _xactId: JsonField = JsonMissing.of(), + @JsonProperty("object_id") @ExcludeMissing objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("created") @ExcludeMissing created: JsonField = JsonMissing.of(), + ) : this(id, _xactId, objectId, objectType, created, mutableMapOf()) + /** * ID of the original event. * @@ -79,7 +78,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Returns the raw JSON value of [id]. @@ -118,24 +117,15 @@ private constructor( */ @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ObjectReference = apply { - if (validated) { - return@apply - } - - id() - _xactId() - objectId() - objectType() - created() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -275,10 +265,46 @@ private constructor( checkRequired("objectId", objectId), checkRequired("objectType", objectType), created, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): ObjectReference = apply { + if (validated) { + return@apply + } + + id() + _xactId() + objectId() + objectType().validate() + created() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (_xactId.asKnown().isPresent) 1 else 0) + + (if (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (created.asKnown().isPresent) 1 else 0) + /** Type of the object the event is originating from. */ class ObjectType @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -393,6 +419,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ObjectType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OnlineScoreConfig.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OnlineScoreConfig.kt index 22191392..e44af8fe 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OnlineScoreConfig.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OnlineScoreConfig.kt @@ -9,11 +9,10 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect +import com.braintrustdata.api.core.allMaxBy import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -27,29 +26,36 @@ 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.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class OnlineScoreConfig -@JsonCreator private constructor( - @JsonProperty("sampling_rate") - @ExcludeMissing - private val samplingRate: JsonField = JsonMissing.of(), - @JsonProperty("scorers") - @ExcludeMissing - private val scorers: JsonField> = JsonMissing.of(), - @JsonProperty("apply_to_root_span") - @ExcludeMissing - private val applyToRootSpan: JsonField = JsonMissing.of(), - @JsonProperty("apply_to_span_names") - @ExcludeMissing - private val applyToSpanNames: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val samplingRate: JsonField, + private val scorers: JsonField>, + private val applyToRootSpan: JsonField, + private val applyToSpanNames: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("sampling_rate") + @ExcludeMissing + samplingRate: JsonField = JsonMissing.of(), + @JsonProperty("scorers") + @ExcludeMissing + scorers: JsonField> = JsonMissing.of(), + @JsonProperty("apply_to_root_span") + @ExcludeMissing + applyToRootSpan: JsonField = JsonMissing.of(), + @JsonProperty("apply_to_span_names") + @ExcludeMissing + applyToSpanNames: JsonField> = JsonMissing.of(), + ) : this(samplingRate, scorers, applyToRootSpan, applyToSpanNames, mutableMapOf()) + /** * The sampling rate for online scoring * @@ -72,8 +78,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun applyToRootSpan(): Optional = - Optional.ofNullable(applyToRootSpan.getNullable("apply_to_root_span")) + fun applyToRootSpan(): Optional = applyToRootSpan.getOptional("apply_to_root_span") /** * Trigger online scoring on any spans with a name in this list @@ -82,7 +87,7 @@ private constructor( * server responded with an unexpected value). */ fun applyToSpanNames(): Optional> = - Optional.ofNullable(applyToSpanNames.getNullable("apply_to_span_names")) + applyToSpanNames.getOptional("apply_to_span_names") /** * Returns the raw JSON value of [samplingRate]. @@ -119,23 +124,15 @@ private constructor( @ExcludeMissing fun _applyToSpanNames(): JsonField> = applyToSpanNames + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): OnlineScoreConfig = apply { - if (validated) { - return@apply - } - - samplingRate() - scorers().forEach { it.validate() } - applyToRootSpan() - applyToSpanNames() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -312,10 +309,44 @@ private constructor( checkRequired("scorers", scorers).map { it.toImmutable() }, applyToRootSpan, (applyToSpanNames ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): OnlineScoreConfig = apply { + if (validated) { + return@apply + } + + samplingRate() + scorers().forEach { it.validate() } + applyToRootSpan() + applyToSpanNames() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (samplingRate.asKnown().isPresent) 1 else 0) + + (scorers.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (applyToRootSpan.asKnown().isPresent) 1 else 0) + + (applyToSpanNames.asKnown().getOrNull()?.size ?: 0) + @JsonDeserialize(using = Scorer.Deserializer::class) @JsonSerialize(using = Scorer.Serializer::class) class Scorer @@ -339,13 +370,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { function != null -> visitor.visitFunction(function) global != null -> visitor.visitGlobal(global) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -368,6 +398,32 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitFunction(function: Function) = function.validity() + + override fun visitGlobal(global: Global) = global.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -420,16 +476,28 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Scorer { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Scorer(function = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Scorer(global = it, _json = json) - } - - return Scorer(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Scorer(function = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Scorer(global = 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 -> Scorer(_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() + } } } @@ -449,20 +517,19 @@ private constructor( } } - @NoAutoDetect class Function - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(id, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -491,21 +558,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Function = apply { - if (validated) { - return@apply - } - - id() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -598,10 +659,41 @@ private constructor( Function( checkRequired("id", id), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Function = apply { + if (validated) { + return@apply + } + + id() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -686,6 +778,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -717,20 +836,19 @@ private constructor( "Function{id=$id, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Global - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(name, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -759,21 +877,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Global = apply { - if (validated) { - return@apply - } - - name() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -866,10 +978,41 @@ private constructor( Global( checkRequired("name", name), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Global = apply { + if (validated) { + return@apply + } + + name() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -954,6 +1097,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Organization.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Organization.kt index 532da10b..d80fcb7f 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Organization.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Organization.kt @@ -6,44 +6,47 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class Organization -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("api_url") - @ExcludeMissing - private val apiUrl: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("is_universal_api") - @ExcludeMissing - private val isUniversalApi: JsonField = JsonMissing.of(), - @JsonProperty("proxy_url") - @ExcludeMissing - private val proxyUrl: JsonField = JsonMissing.of(), - @JsonProperty("realtime_url") - @ExcludeMissing - private val realtimeUrl: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val name: JsonField, + private val apiUrl: JsonField, + private val created: JsonField, + private val isUniversalApi: JsonField, + private val proxyUrl: JsonField, + private val realtimeUrl: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("api_url") @ExcludeMissing apiUrl: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("is_universal_api") + @ExcludeMissing + isUniversalApi: JsonField = JsonMissing.of(), + @JsonProperty("proxy_url") @ExcludeMissing proxyUrl: JsonField = JsonMissing.of(), + @JsonProperty("realtime_url") + @ExcludeMissing + realtimeUrl: JsonField = JsonMissing.of(), + ) : this(id, name, apiUrl, created, isUniversalApi, proxyUrl, realtimeUrl, mutableMapOf()) + /** * Unique identifier for the organization * @@ -64,7 +67,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun apiUrl(): Optional = Optional.ofNullable(apiUrl.getNullable("api_url")) + fun apiUrl(): Optional = apiUrl.getOptional("api_url") /** * Date of organization creation @@ -72,27 +75,25 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun isUniversalApi(): Optional = - Optional.ofNullable(isUniversalApi.getNullable("is_universal_api")) + fun isUniversalApi(): Optional = isUniversalApi.getOptional("is_universal_api") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun proxyUrl(): Optional = Optional.ofNullable(proxyUrl.getNullable("proxy_url")) + fun proxyUrl(): Optional = proxyUrl.getOptional("proxy_url") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun realtimeUrl(): Optional = - Optional.ofNullable(realtimeUrl.getNullable("realtime_url")) + fun realtimeUrl(): Optional = realtimeUrl.getOptional("realtime_url") /** * Returns the raw JSON value of [id]. @@ -147,26 +148,15 @@ private constructor( @ExcludeMissing fun _realtimeUrl(): JsonField = realtimeUrl + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Organization = apply { - if (validated) { - return@apply - } - - id() - name() - apiUrl() - created() - isUniversalApi() - proxyUrl() - realtimeUrl() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -351,10 +341,50 @@ private constructor( isUniversalApi, proxyUrl, realtimeUrl, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Organization = apply { + if (validated) { + return@apply + } + + id() + name() + apiUrl() + created() + isUniversalApi() + proxyUrl() + realtimeUrl() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (apiUrl.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (isUniversalApi.asKnown().isPresent) 1 else 0) + + (if (proxyUrl.asKnown().isPresent) 1 else 0) + + (if (realtimeUrl.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationDeleteParams.kt index a6d936fa..7247f8ec 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationDeleteParams.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,26 +23,11 @@ private constructor( /** Organization id */ fun organizationId(): String = organizationId - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> organizationId - else -> "" - } - } + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -61,7 +45,6 @@ private constructor( } /** A builder for [OrganizationDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var organizationId: String? = null @@ -222,6 +205,19 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> organizationId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListPage.kt index 6683eed2..f8d68211 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListPage.kt @@ -2,171 +2,115 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.OrganizationService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all organizations. The organizations are sorted by creation date, with the most - * recently-created organizations coming first - */ +/** @see [OrganizationService.list] */ class OrganizationListPage private constructor( - private val organizationsService: OrganizationService, + private val service: OrganizationService, private val params: OrganizationListParams, - private val response: Response, + private val response: OrganizationListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [OrganizationListPageResponse], but gracefully handles missing data. + * + * @see [OrganizationListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is OrganizationListPage && organizationsService == other.organizationsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(organizationsService, params, response) /* spotless:on */ - - override fun toString() = - "OrganizationListPage{organizationsService=$organizationsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - OrganizationListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - OrganizationListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { organizationsService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of( - organizationsService: OrganizationService, - params: OrganizationListParams, - response: Response, - ) = OrganizationListPage(organizationsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") - private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): OrganizationListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): OrganizationListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [OrganizationListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [OrganizationListPage]. */ + class Builder internal constructor() { - companion object { + private var service: OrganizationService? = null + private var params: OrganizationListParams? = null + private var response: OrganizationListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [OrganizationListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(organizationListPage: OrganizationListPage) = apply { + service = organizationListPage.service + params = organizationListPage.params + response = organizationListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: OrganizationService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: OrganizationListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: OrganizationListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [OrganizationListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): OrganizationListPage = + OrganizationListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: OrganizationListPage) : Iterable { @@ -187,4 +131,17 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is OrganizationListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "OrganizationListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListPageAsync.kt index 0c6503ba..8d1fb8a2 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListPageAsync.kt @@ -2,176 +2,119 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.OrganizationServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all organizations. The organizations are sorted by creation date, with the most - * recently-created organizations coming first - */ +/** @see [OrganizationServiceAsync.list] */ class OrganizationListPageAsync private constructor( - private val organizationsService: OrganizationServiceAsync, + private val service: OrganizationServiceAsync, private val params: OrganizationListParams, - private val response: Response, + private val response: OrganizationListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [OrganizationListPageResponse], but gracefully handles missing data. + * + * @see [OrganizationListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is OrganizationListPageAsync && organizationsService == other.organizationsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(organizationsService, params, response) /* spotless:on */ - - override fun toString() = - "OrganizationListPageAsync{organizationsService=$organizationsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - OrganizationListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - OrganizationListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { organizationsService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of( - organizationsService: OrganizationServiceAsync, - params: OrganizationListParams, - response: Response, - ) = OrganizationListPageAsync(organizationsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") - private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): OrganizationListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): OrganizationListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [OrganizationListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [OrganizationListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: OrganizationServiceAsync? = null + private var params: OrganizationListParams? = null + private var response: OrganizationListPageResponse? = null - /** - * Returns a mutable builder for constructing an instance of - * [OrganizationListPageAsync]. - */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(organizationListPageAsync: OrganizationListPageAsync) = apply { + service = organizationListPageAsync.service + params = organizationListPageAsync.params + response = organizationListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: OrganizationServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: OrganizationListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: OrganizationListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [OrganizationListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): OrganizationListPageAsync = + OrganizationListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: OrganizationListPageAsync) { @@ -199,4 +142,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is OrganizationListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "OrganizationListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListPageResponse.kt new file mode 100644 index 00000000..2bd0dfe3 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListPageResponse.kt @@ -0,0 +1,194 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class OrganizationListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") + @ExcludeMissing + objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of organization objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [OrganizationListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OrganizationListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(organizationListPageResponse: OrganizationListPageResponse) = apply { + objects = organizationListPageResponse.objects.map { it.toMutableList() } + additionalProperties = organizationListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of organization objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [Organization] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: Organization) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [OrganizationListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): OrganizationListPageResponse = + OrganizationListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): OrganizationListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is OrganizationListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "OrganizationListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListParams.kt index ee4d5674..af6f46c8 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListParams.kt @@ -2,22 +2,10 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -71,30 +59,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - endingBefore?.let { put("ending_before", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - orgName?.let { put("org_name", it) } - startingAfter?.let { put("starting_after", it) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -106,7 +70,6 @@ private constructor( } /** A builder for [OrganizationListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var endingBefore: String? = null @@ -302,17 +265,38 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + endingBefore?.let { put("ending_before", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + orgName?.let { put("org_name", it) } + startingAfter?.let { put("starting_after", it) } + putAll(additionalQueryParams) + } + .build() + /** * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -327,15 +311,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -351,7 +332,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -368,51 +348,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationMemberUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationMemberUpdateParams.kt index 11ffafd2..0cb08253 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationMemberUpdateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationMemberUpdateParams.kt @@ -6,18 +6,17 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -100,40 +99,279 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): OrganizationMemberUpdateParams = builder().build() + + /** + * Returns a mutable builder for constructing an instance of + * [OrganizationMemberUpdateParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OrganizationMemberUpdateParams]. */ + 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(organizationMemberUpdateParams: OrganizationMemberUpdateParams) = apply { + body = organizationMemberUpdateParams.body.toBuilder() + additionalHeaders = organizationMemberUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = organizationMemberUpdateParams.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: + * - [inviteUsers] + * - [orgId] + * - [orgName] + * - [removeUsers] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Users to invite to the organization */ + fun inviteUsers(inviteUsers: InviteUsers?) = apply { body.inviteUsers(inviteUsers) } + + /** Alias for calling [Builder.inviteUsers] with `inviteUsers.orElse(null)`. */ + fun inviteUsers(inviteUsers: Optional) = inviteUsers(inviteUsers.getOrNull()) + + /** + * Sets [Builder.inviteUsers] to an arbitrary JSON value. + * + * You should usually call [Builder.inviteUsers] with a well-typed [InviteUsers] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun inviteUsers(inviteUsers: JsonField) = apply { + body.inviteUsers(inviteUsers) + } + + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, or in case you want to explicitly assert + * the organization you are modifying, you may specify the id of the organization. + */ + fun orgId(orgId: String?) = apply { body.orgId(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 { body.orgId(orgId) } + + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, or in case you want to explicitly assert + * the organization you are modifying, you may specify the name of the organization. + */ + fun orgName(orgName: String?) = apply { body.orgName(orgName) } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** + * Sets [Builder.orgName] to an arbitrary JSON value. + * + * You should usually call [Builder.orgName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun orgName(orgName: JsonField) = apply { body.orgName(orgName) } + + /** Users to remove from the organization */ + fun removeUsers(removeUsers: RemoveUsers?) = apply { body.removeUsers(removeUsers) } + + /** Alias for calling [Builder.removeUsers] with `removeUsers.orElse(null)`. */ + fun removeUsers(removeUsers: Optional) = removeUsers(removeUsers.getOrNull()) + + /** + * Sets [Builder.removeUsers] to an arbitrary JSON value. + * + * You should usually call [Builder.removeUsers] with a well-typed [RemoveUsers] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun removeUsers(removeUsers: JsonField) = apply { + body.removeUsers(removeUsers) + } + + 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 [OrganizationMemberUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): OrganizationMemberUpdateParams = + OrganizationMemberUpdateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body override fun _headers(): Headers = additionalHeaders override fun _queryParams(): QueryParams = additionalQueryParams - @NoAutoDetect class Body - @JsonCreator private constructor( - @JsonProperty("invite_users") - @ExcludeMissing - private val inviteUsers: JsonField = JsonMissing.of(), - @JsonProperty("org_id") - @ExcludeMissing - private val orgId: JsonField = JsonMissing.of(), - @JsonProperty("org_name") - @ExcludeMissing - private val orgName: JsonField = JsonMissing.of(), - @JsonProperty("remove_users") - @ExcludeMissing - private val removeUsers: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val inviteUsers: JsonField, + private val orgId: JsonField, + private val orgName: JsonField, + private val removeUsers: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("invite_users") + @ExcludeMissing + inviteUsers: JsonField = JsonMissing.of(), + @JsonProperty("org_id") @ExcludeMissing orgId: JsonField = JsonMissing.of(), + @JsonProperty("org_name") @ExcludeMissing orgName: JsonField = JsonMissing.of(), + @JsonProperty("remove_users") + @ExcludeMissing + removeUsers: JsonField = JsonMissing.of(), + ) : this(inviteUsers, orgId, orgName, removeUsers, mutableMapOf()) + /** * Users to invite to the organization * * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun inviteUsers(): Optional = - Optional.ofNullable(inviteUsers.getNullable("invite_users")) + fun inviteUsers(): Optional = inviteUsers.getOptional("invite_users") /** * For nearly all users, this parameter should be unnecessary. But in the rare case that @@ -143,7 +381,7 @@ private constructor( * @throws BraintrustInvalidDataException 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 orgId(): Optional = orgId.getOptional("org_id") /** * For nearly all users, this parameter should be unnecessary. But in the rare case that @@ -153,7 +391,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun orgName(): Optional = Optional.ofNullable(orgName.getNullable("org_name")) + fun orgName(): Optional = orgName.getOptional("org_name") /** * Users to remove from the organization @@ -161,8 +399,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun removeUsers(): Optional = - Optional.ofNullable(removeUsers.getNullable("remove_users")) + fun removeUsers(): Optional = removeUsers.getOptional("remove_users") /** * Returns the raw JSON value of [inviteUsers]. @@ -196,23 +433,15 @@ private constructor( @ExcludeMissing fun _removeUsers(): JsonField = removeUsers + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - inviteUsers().ifPresent { it.validate() } - orgId() - orgName() - removeUsers().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -267,368 +496,188 @@ private constructor( */ 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 } - - /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, or in case you want to explicitly - * assert the organization you are modifying, you may specify the name of the - * organization. - */ - fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) - - /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ - fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) - - /** - * Sets [Builder.orgName] to an arbitrary JSON value. - * - * You should usually call [Builder.orgName] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun orgName(orgName: JsonField) = apply { this.orgName = orgName } - - /** Users to remove from the organization */ - fun removeUsers(removeUsers: RemoveUsers?) = - removeUsers(JsonField.ofNullable(removeUsers)) - - /** Alias for calling [Builder.removeUsers] with `removeUsers.orElse(null)`. */ - fun removeUsers(removeUsers: Optional) = - removeUsers(removeUsers.getOrNull()) - - /** - * Sets [Builder.removeUsers] to an arbitrary JSON value. - * - * You should usually call [Builder.removeUsers] with a well-typed [RemoveUsers] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun removeUsers(removeUsers: JsonField) = apply { - this.removeUsers = removeUsers - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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. - */ - fun build(): Body = - Body(inviteUsers, orgId, orgName, removeUsers, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && inviteUsers == other.inviteUsers && orgId == other.orgId && orgName == other.orgName && removeUsers == other.removeUsers && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(inviteUsers, orgId, orgName, removeUsers, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{inviteUsers=$inviteUsers, orgId=$orgId, orgName=$orgName, removeUsers=$removeUsers, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun none(): OrganizationMemberUpdateParams = builder().build() - - /** - * Returns a mutable builder for constructing an instance of - * [OrganizationMemberUpdateParams]. - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [OrganizationMemberUpdateParams]. */ - @NoAutoDetect - 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(organizationMemberUpdateParams: OrganizationMemberUpdateParams) = apply { - body = organizationMemberUpdateParams.body.toBuilder() - additionalHeaders = organizationMemberUpdateParams.additionalHeaders.toBuilder() - additionalQueryParams = organizationMemberUpdateParams.additionalQueryParams.toBuilder() - } - - /** Users to invite to the organization */ - fun inviteUsers(inviteUsers: InviteUsers?) = apply { body.inviteUsers(inviteUsers) } - - /** Alias for calling [Builder.inviteUsers] with `inviteUsers.orElse(null)`. */ - fun inviteUsers(inviteUsers: Optional) = inviteUsers(inviteUsers.getOrNull()) - - /** - * Sets [Builder.inviteUsers] to an arbitrary JSON value. - * - * You should usually call [Builder.inviteUsers] with a well-typed [InviteUsers] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun inviteUsers(inviteUsers: JsonField) = apply { - body.inviteUsers(inviteUsers) - } - - /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, or in case you want to explicitly assert - * the organization you are modifying, you may specify the id of the organization. - */ - fun orgId(orgId: String?) = apply { body.orgId(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 { body.orgId(orgId) } - - /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, or in case you want to explicitly assert - * the organization you are modifying, you may specify the name of the organization. - */ - fun orgName(orgName: String?) = apply { body.orgName(orgName) } - - /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ - fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) - - /** - * Sets [Builder.orgName] to an arbitrary JSON value. - * - * You should usually call [Builder.orgName] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun orgName(orgName: JsonField) = apply { body.orgName(orgName) } - - /** Users to remove from the organization */ - fun removeUsers(removeUsers: RemoveUsers?) = apply { body.removeUsers(removeUsers) } - - /** Alias for calling [Builder.removeUsers] with `removeUsers.orElse(null)`. */ - fun removeUsers(removeUsers: Optional) = removeUsers(removeUsers.getOrNull()) - - /** - * Sets [Builder.removeUsers] to an arbitrary JSON value. - * - * You should usually call [Builder.removeUsers] with a well-typed [RemoveUsers] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun removeUsers(removeUsers: JsonField) = apply { - body.removeUsers(removeUsers) - } - - 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) - } + /** Alias for calling [Builder.orgId] with `orgId.orElse(null)`. */ + fun orgId(orgId: Optional) = orgId(orgId.getOrNull()) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * 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 putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, or in case you want to explicitly + * assert the organization you are modifying, you may specify the name of the + * organization. + */ + fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.orgName] to an arbitrary JSON value. + * + * You should usually call [Builder.orgName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun orgName(orgName: JsonField) = apply { this.orgName = orgName } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** Users to remove from the organization */ + fun removeUsers(removeUsers: RemoveUsers?) = + removeUsers(JsonField.ofNullable(removeUsers)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.removeUsers] with `removeUsers.orElse(null)`. */ + fun removeUsers(removeUsers: Optional) = + removeUsers(removeUsers.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.removeUsers] to an arbitrary JSON value. + * + * You should usually call [Builder.removeUsers] with a well-typed [RemoveUsers] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun removeUsers(removeUsers: JsonField) = apply { + this.removeUsers = removeUsers + } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body(inviteUsers, orgId, orgName, removeUsers, additionalProperties.toMutableMap()) } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + private var validated: Boolean = false - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun validate(): Body = apply { + if (validated) { + return@apply } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) + inviteUsers().ifPresent { it.validate() } + orgId() + orgName() + removeUsers().ifPresent { it.validate() } + validated = true } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (inviteUsers.asKnown().getOrNull()?.validity() ?: 0) + + (if (orgId.asKnown().isPresent) 1 else 0) + + (if (orgName.asKnown().isPresent) 1 else 0) + + (removeUsers.asKnown().getOrNull()?.validity() ?: 0) - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + return /* spotless:off */ other is Body && inviteUsers == other.inviteUsers && orgId == other.orgId && orgName == other.orgName && removeUsers == other.removeUsers && additionalProperties == other.additionalProperties /* spotless:on */ } - /** - * Returns an immutable instance of [OrganizationMemberUpdateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): OrganizationMemberUpdateParams = - OrganizationMemberUpdateParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(inviteUsers, orgId, orgName, removeUsers, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{inviteUsers=$inviteUsers, orgId=$orgId, orgName=$orgName, removeUsers=$removeUsers, additionalProperties=$additionalProperties}" } /** Users to invite to the organization */ - @NoAutoDetect class InviteUsers - @JsonCreator private constructor( - @JsonProperty("emails") - @ExcludeMissing - private val emails: JsonField> = JsonMissing.of(), - @JsonProperty("group_id") - @ExcludeMissing - private val groupId: JsonField = JsonMissing.of(), - @JsonProperty("group_ids") - @ExcludeMissing - private val groupIds: JsonField> = JsonMissing.of(), - @JsonProperty("group_name") - @ExcludeMissing - private val groupName: JsonField = JsonMissing.of(), - @JsonProperty("group_names") - @ExcludeMissing - private val groupNames: JsonField> = JsonMissing.of(), - @JsonProperty("ids") - @ExcludeMissing - private val ids: JsonField> = JsonMissing.of(), - @JsonProperty("send_invite_emails") - @ExcludeMissing - private val sendInviteEmails: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val emails: JsonField>, + private val groupId: JsonField, + private val groupIds: JsonField>, + private val groupName: JsonField, + private val groupNames: JsonField>, + private val ids: JsonField>, + private val sendInviteEmails: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("emails") + @ExcludeMissing + emails: JsonField> = JsonMissing.of(), + @JsonProperty("group_id") @ExcludeMissing groupId: JsonField = JsonMissing.of(), + @JsonProperty("group_ids") + @ExcludeMissing + groupIds: JsonField> = JsonMissing.of(), + @JsonProperty("group_name") + @ExcludeMissing + groupName: JsonField = JsonMissing.of(), + @JsonProperty("group_names") + @ExcludeMissing + groupNames: JsonField> = JsonMissing.of(), + @JsonProperty("ids") @ExcludeMissing ids: JsonField> = JsonMissing.of(), + @JsonProperty("send_invite_emails") + @ExcludeMissing + sendInviteEmails: JsonField = JsonMissing.of(), + ) : this( + emails, + groupId, + groupIds, + groupName, + groupNames, + ids, + sendInviteEmails, + mutableMapOf(), + ) + /** * Emails of users to invite * * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun emails(): Optional> = Optional.ofNullable(emails.getNullable("emails")) + fun emails(): Optional> = emails.getOptional("emails") /** * Singular form of group_ids @@ -636,7 +685,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun groupId(): Optional = Optional.ofNullable(groupId.getNullable("group_id")) + fun groupId(): Optional = groupId.getOptional("group_id") /** * Optional list of group ids to add newly-invited users to. @@ -644,8 +693,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun groupIds(): Optional> = - Optional.ofNullable(groupIds.getNullable("group_ids")) + fun groupIds(): Optional> = groupIds.getOptional("group_ids") /** * Singular form of group_names @@ -653,7 +701,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun groupName(): Optional = Optional.ofNullable(groupName.getNullable("group_name")) + fun groupName(): Optional = groupName.getOptional("group_name") /** * Optional list of group names to add newly-invited users to. @@ -661,8 +709,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun groupNames(): Optional> = - Optional.ofNullable(groupNames.getNullable("group_names")) + fun groupNames(): Optional> = groupNames.getOptional("group_names") /** * Ids of existing users to invite @@ -670,7 +717,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun ids(): Optional> = Optional.ofNullable(ids.getNullable("ids")) + fun ids(): Optional> = ids.getOptional("ids") /** * If true, send invite emails to the users who wore actually added @@ -679,7 +726,7 @@ private constructor( * the server responded with an unexpected value). */ fun sendInviteEmails(): Optional = - Optional.ofNullable(sendInviteEmails.getNullable("send_invite_emails")) + sendInviteEmails.getOptional("send_invite_emails") /** * Returns the raw JSON value of [emails]. @@ -737,26 +784,15 @@ private constructor( @ExcludeMissing fun _sendInviteEmails(): JsonField = sendInviteEmails + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): InviteUsers = apply { - if (validated) { - return@apply - } - - emails() - groupId() - groupIds() - groupName() - groupNames() - ids() - sendInviteEmails() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -995,10 +1031,51 @@ private constructor( (groupNames ?: JsonMissing.of()).map { it.toImmutable() }, (ids ?: JsonMissing.of()).map { it.toImmutable() }, sendInviteEmails, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): InviteUsers = apply { + if (validated) { + return@apply + } + + emails() + groupId() + groupIds() + groupName() + groupNames() + ids() + sendInviteEmails() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (emails.asKnown().getOrNull()?.size ?: 0) + + (if (groupId.asKnown().isPresent) 1 else 0) + + (groupIds.asKnown().getOrNull()?.size ?: 0) + + (if (groupName.asKnown().isPresent) 1 else 0) + + (groupNames.asKnown().getOrNull()?.size ?: 0) + + (ids.asKnown().getOrNull()?.size ?: 0) + + (if (sendInviteEmails.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1018,27 +1095,28 @@ private constructor( } /** Users to remove from the organization */ - @NoAutoDetect class RemoveUsers - @JsonCreator private constructor( - @JsonProperty("emails") - @ExcludeMissing - private val emails: JsonField> = JsonMissing.of(), - @JsonProperty("ids") - @ExcludeMissing - private val ids: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val emails: JsonField>, + private val ids: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("emails") + @ExcludeMissing + emails: JsonField> = JsonMissing.of(), + @JsonProperty("ids") @ExcludeMissing ids: JsonField> = JsonMissing.of(), + ) : this(emails, ids, mutableMapOf()) + /** * Emails of users to remove * * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun emails(): Optional> = Optional.ofNullable(emails.getNullable("emails")) + fun emails(): Optional> = emails.getOptional("emails") /** * Ids of users to remove @@ -1046,7 +1124,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun ids(): Optional> = Optional.ofNullable(ids.getNullable("ids")) + fun ids(): Optional> = ids.getOptional("ids") /** * Returns the raw JSON value of [emails]. @@ -1062,21 +1140,15 @@ private constructor( */ @JsonProperty("ids") @ExcludeMissing fun _ids(): JsonField> = ids + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): RemoveUsers = apply { - if (validated) { - return@apply - } - - emails() - ids() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1183,10 +1255,40 @@ private constructor( RemoveUsers( (emails ?: JsonMissing.of()).map { it.toImmutable() }, (ids ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): RemoveUsers = apply { + if (validated) { + return@apply + } + + emails() + ids() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (emails.asKnown().getOrNull()?.size ?: 0) + (ids.asKnown().getOrNull()?.size ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationRetrieveParams.kt index 86b3cebc..6be05478 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> organizationId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [OrganizationRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var organizationId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> organizationId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationUpdateParams.kt index 36741dd2..83ffe1a5 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationUpdateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationUpdateParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -111,549 +109,589 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders + fun toBuilder() = Builder().from(this) - override fun _queryParams(): QueryParams = additionalQueryParams + companion object { - fun getPathParam(index: Int): String { - return when (index) { - 0 -> organizationId - else -> "" - } + /** + * Returns a mutable builder for constructing an instance of [OrganizationUpdateParams]. + * + * The following fields are required: + * ```java + * .organizationId() + * ``` + */ + @JvmStatic fun builder() = Builder() } - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("api_url") - @ExcludeMissing - private val apiUrl: JsonField = JsonMissing.of(), - @JsonProperty("is_universal_api") - @ExcludeMissing - private val isUniversalApi: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("proxy_url") - @ExcludeMissing - private val proxyUrl: JsonField = JsonMissing.of(), - @JsonProperty("realtime_url") - @ExcludeMissing - private val realtimeUrl: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** A builder for [OrganizationUpdateParams]. */ + class Builder internal constructor() { - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun apiUrl(): Optional = Optional.ofNullable(apiUrl.getNullable("api_url")) + private var organizationId: String? = null + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun isUniversalApi(): Optional = - Optional.ofNullable(isUniversalApi.getNullable("is_universal_api")) + @JvmSynthetic + internal fun from(organizationUpdateParams: OrganizationUpdateParams) = apply { + organizationId = organizationUpdateParams.organizationId + body = organizationUpdateParams.body.toBuilder() + additionalHeaders = organizationUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = organizationUpdateParams.additionalQueryParams.toBuilder() + } + + /** Organization id */ + fun organizationId(organizationId: String) = apply { this.organizationId = organizationId } /** - * Name of the organization + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [apiUrl] + * - [isUniversalApi] + * - [name] + * - [proxyUrl] + * - [realtimeUrl] + * - etc. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun body(body: Body) = apply { this.body = body.toBuilder() } - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun proxyUrl(): Optional = Optional.ofNullable(proxyUrl.getNullable("proxy_url")) + fun apiUrl(apiUrl: String?) = apply { body.apiUrl(apiUrl) } + + /** Alias for calling [Builder.apiUrl] with `apiUrl.orElse(null)`. */ + fun apiUrl(apiUrl: Optional) = apiUrl(apiUrl.getOrNull()) /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * Sets [Builder.apiUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.apiUrl] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - fun realtimeUrl(): Optional = - Optional.ofNullable(realtimeUrl.getNullable("realtime_url")) + fun apiUrl(apiUrl: JsonField) = apply { body.apiUrl(apiUrl) } + + fun isUniversalApi(isUniversalApi: Boolean?) = apply { body.isUniversalApi(isUniversalApi) } /** - * Returns the raw JSON value of [apiUrl]. + * Alias for [Builder.isUniversalApi]. * - * Unlike [apiUrl], this method doesn't throw if the JSON field has an unexpected type. + * This unboxed primitive overload exists for backwards compatibility. */ - @JsonProperty("api_url") @ExcludeMissing fun _apiUrl(): JsonField = apiUrl + fun isUniversalApi(isUniversalApi: Boolean) = isUniversalApi(isUniversalApi as Boolean?) + + /** Alias for calling [Builder.isUniversalApi] with `isUniversalApi.orElse(null)`. */ + fun isUniversalApi(isUniversalApi: Optional) = + isUniversalApi(isUniversalApi.getOrNull()) /** - * Returns the raw JSON value of [isUniversalApi]. + * Sets [Builder.isUniversalApi] to an arbitrary JSON value. * - * Unlike [isUniversalApi], this method doesn't throw if the JSON field has an unexpected - * type. + * You should usually call [Builder.isUniversalApi] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("is_universal_api") - @ExcludeMissing - fun _isUniversalApi(): JsonField = isUniversalApi + fun isUniversalApi(isUniversalApi: JsonField) = apply { + body.isUniversalApi(isUniversalApi) + } + + /** Name of the organization */ + fun name(name: String?) = apply { body.name(name) } + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) /** - * Returns the raw JSON value of [name]. + * Sets [Builder.name] to an arbitrary JSON value. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun name(name: JsonField) = apply { body.name(name) } + + fun proxyUrl(proxyUrl: String?) = apply { body.proxyUrl(proxyUrl) } + + /** Alias for calling [Builder.proxyUrl] with `proxyUrl.orElse(null)`. */ + fun proxyUrl(proxyUrl: Optional) = proxyUrl(proxyUrl.getOrNull()) /** - * Returns the raw JSON value of [proxyUrl]. + * Sets [Builder.proxyUrl] to an arbitrary JSON value. * - * Unlike [proxyUrl], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.proxyUrl] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("proxy_url") @ExcludeMissing fun _proxyUrl(): JsonField = proxyUrl + fun proxyUrl(proxyUrl: JsonField) = apply { body.proxyUrl(proxyUrl) } + + fun realtimeUrl(realtimeUrl: String?) = apply { body.realtimeUrl(realtimeUrl) } + + /** Alias for calling [Builder.realtimeUrl] with `realtimeUrl.orElse(null)`. */ + fun realtimeUrl(realtimeUrl: Optional) = realtimeUrl(realtimeUrl.getOrNull()) /** - * Returns the raw JSON value of [realtimeUrl]. + * Sets [Builder.realtimeUrl] to an arbitrary JSON value. * - * Unlike [realtimeUrl], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.realtimeUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("realtime_url") - @ExcludeMissing - fun _realtimeUrl(): JsonField = realtimeUrl + fun realtimeUrl(realtimeUrl: JsonField) = apply { body.realtimeUrl(realtimeUrl) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var validated: Boolean = false + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - fun validate(): Body = apply { - if (validated) { - return@apply + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - apiUrl() - isUniversalApi() - name() - proxyUrl() - realtimeUrl() - validated = true - } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun toBuilder() = Builder().from(this) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - companion object { + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Returns a mutable builder for constructing an instance of [Body]. */ - @JvmStatic fun builder() = Builder() + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - private var apiUrl: JsonField = JsonMissing.of() - private var isUniversalApi: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var proxyUrl: JsonField = JsonMissing.of() - private var realtimeUrl: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - @JvmSynthetic - internal fun from(body: Body) = apply { - apiUrl = body.apiUrl - isUniversalApi = body.isUniversalApi - name = body.name - proxyUrl = body.proxyUrl - realtimeUrl = body.realtimeUrl - additionalProperties = body.additionalProperties.toMutableMap() - } + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - fun apiUrl(apiUrl: String?) = apiUrl(JsonField.ofNullable(apiUrl)) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.apiUrl] with `apiUrl.orElse(null)`. */ - fun apiUrl(apiUrl: Optional) = apiUrl(apiUrl.getOrNull()) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * Sets [Builder.apiUrl] to an arbitrary JSON value. - * - * You should usually call [Builder.apiUrl] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun apiUrl(apiUrl: JsonField) = apply { this.apiUrl = apiUrl } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - fun isUniversalApi(isUniversalApi: Boolean?) = - isUniversalApi(JsonField.ofNullable(isUniversalApi)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Alias for [Builder.isUniversalApi]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun isUniversalApi(isUniversalApi: Boolean) = isUniversalApi(isUniversalApi as Boolean?) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.isUniversalApi] with `isUniversalApi.orElse(null)`. */ - fun isUniversalApi(isUniversalApi: Optional) = - isUniversalApi(isUniversalApi.getOrNull()) + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - /** - * Sets [Builder.isUniversalApi] to an arbitrary JSON value. - * - * You should usually call [Builder.isUniversalApi] with a well-typed [Boolean] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun isUniversalApi(isUniversalApi: JsonField) = apply { - this.isUniversalApi = isUniversalApi - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - /** Name of the organization */ - fun name(name: String?) = name(JsonField.ofNullable(name)) + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - /** 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 proxyUrl(proxyUrl: String?) = proxyUrl(JsonField.ofNullable(proxyUrl)) - - /** Alias for calling [Builder.proxyUrl] with `proxyUrl.orElse(null)`. */ - fun proxyUrl(proxyUrl: Optional) = proxyUrl(proxyUrl.getOrNull()) - - /** - * Sets [Builder.proxyUrl] to an arbitrary JSON value. - * - * You should usually call [Builder.proxyUrl] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun proxyUrl(proxyUrl: JsonField) = apply { this.proxyUrl = proxyUrl } - - fun realtimeUrl(realtimeUrl: String?) = realtimeUrl(JsonField.ofNullable(realtimeUrl)) - - /** Alias for calling [Builder.realtimeUrl] with `realtimeUrl.orElse(null)`. */ - fun realtimeUrl(realtimeUrl: Optional) = realtimeUrl(realtimeUrl.getOrNull()) - - /** - * Sets [Builder.realtimeUrl] to an arbitrary JSON value. - * - * You should usually call [Builder.realtimeUrl] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun realtimeUrl(realtimeUrl: JsonField) = apply { - this.realtimeUrl = realtimeUrl - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Body = - Body( - apiUrl, - isUniversalApi, - name, - proxyUrl, - realtimeUrl, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && apiUrl == other.apiUrl && isUniversalApi == other.isUniversalApi && name == other.name && proxyUrl == other.proxyUrl && realtimeUrl == other.realtimeUrl && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(apiUrl, isUniversalApi, name, proxyUrl, realtimeUrl, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{apiUrl=$apiUrl, isUniversalApi=$isUniversalApi, name=$name, proxyUrl=$proxyUrl, realtimeUrl=$realtimeUrl, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [OrganizationUpdateParams]. + * Returns an immutable instance of [OrganizationUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java * .organizationId() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): OrganizationUpdateParams = + OrganizationUpdateParams( + checkRequired("organizationId", organizationId), + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [OrganizationUpdateParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var organizationId: String? = null - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + fun _body(): Body = body - @JvmSynthetic - internal fun from(organizationUpdateParams: OrganizationUpdateParams) = apply { - organizationId = organizationUpdateParams.organizationId - body = organizationUpdateParams.body.toBuilder() - additionalHeaders = organizationUpdateParams.additionalHeaders.toBuilder() - additionalQueryParams = organizationUpdateParams.additionalQueryParams.toBuilder() + fun _pathParam(index: Int): String = + when (index) { + 0 -> organizationId + else -> "" } - /** Organization id */ - fun organizationId(organizationId: String) = apply { this.organizationId = organizationId } + override fun _headers(): Headers = additionalHeaders - fun apiUrl(apiUrl: String?) = apply { body.apiUrl(apiUrl) } + override fun _queryParams(): QueryParams = additionalQueryParams - /** Alias for calling [Builder.apiUrl] with `apiUrl.orElse(null)`. */ - fun apiUrl(apiUrl: Optional) = apiUrl(apiUrl.getOrNull()) + class Body + private constructor( + private val apiUrl: JsonField, + private val isUniversalApi: JsonField, + private val name: JsonField, + private val proxyUrl: JsonField, + private val realtimeUrl: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("api_url") @ExcludeMissing apiUrl: JsonField = JsonMissing.of(), + @JsonProperty("is_universal_api") + @ExcludeMissing + isUniversalApi: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("proxy_url") + @ExcludeMissing + proxyUrl: JsonField = JsonMissing.of(), + @JsonProperty("realtime_url") + @ExcludeMissing + realtimeUrl: JsonField = JsonMissing.of(), + ) : this(apiUrl, isUniversalApi, name, proxyUrl, realtimeUrl, mutableMapOf()) /** - * Sets [Builder.apiUrl] to an arbitrary JSON value. - * - * You should usually call [Builder.apiUrl] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun apiUrl(apiUrl: JsonField) = apply { body.apiUrl(apiUrl) } - - fun isUniversalApi(isUniversalApi: Boolean?) = apply { body.isUniversalApi(isUniversalApi) } + fun apiUrl(): Optional = apiUrl.getOptional("api_url") /** - * Alias for [Builder.isUniversalApi]. - * - * This unboxed primitive overload exists for backwards compatibility. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun isUniversalApi(isUniversalApi: Boolean) = isUniversalApi(isUniversalApi as Boolean?) - - /** Alias for calling [Builder.isUniversalApi] with `isUniversalApi.orElse(null)`. */ - fun isUniversalApi(isUniversalApi: Optional) = - isUniversalApi(isUniversalApi.getOrNull()) + fun isUniversalApi(): Optional = isUniversalApi.getOptional("is_universal_api") /** - * Sets [Builder.isUniversalApi] to an arbitrary JSON value. + * Name of the organization * - * You should usually call [Builder.isUniversalApi] with a well-typed [Boolean] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun isUniversalApi(isUniversalApi: JsonField) = apply { - body.isUniversalApi(isUniversalApi) - } + fun name(): Optional = name.getOptional("name") - /** Name of the organization */ - fun name(name: String?) = apply { body.name(name) } + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun proxyUrl(): Optional = proxyUrl.getOptional("proxy_url") - /** Alias for calling [Builder.name] with `name.orElse(null)`. */ - fun name(name: Optional) = name(name.getOrNull()) + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun realtimeUrl(): Optional = realtimeUrl.getOptional("realtime_url") /** - * Sets [Builder.name] to an arbitrary JSON value. + * Returns the raw JSON value of [apiUrl]. * - * 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. + * Unlike [apiUrl], this method doesn't throw if the JSON field has an unexpected type. */ - fun name(name: JsonField) = apply { body.name(name) } - - fun proxyUrl(proxyUrl: String?) = apply { body.proxyUrl(proxyUrl) } - - /** Alias for calling [Builder.proxyUrl] with `proxyUrl.orElse(null)`. */ - fun proxyUrl(proxyUrl: Optional) = proxyUrl(proxyUrl.getOrNull()) + @JsonProperty("api_url") @ExcludeMissing fun _apiUrl(): JsonField = apiUrl /** - * Sets [Builder.proxyUrl] to an arbitrary JSON value. + * Returns the raw JSON value of [isUniversalApi]. * - * You should usually call [Builder.proxyUrl] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [isUniversalApi], this method doesn't throw if the JSON field has an unexpected + * type. */ - fun proxyUrl(proxyUrl: JsonField) = apply { body.proxyUrl(proxyUrl) } + @JsonProperty("is_universal_api") + @ExcludeMissing + fun _isUniversalApi(): JsonField = isUniversalApi - fun realtimeUrl(realtimeUrl: String?) = apply { body.realtimeUrl(realtimeUrl) } + /** + * 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 - /** Alias for calling [Builder.realtimeUrl] with `realtimeUrl.orElse(null)`. */ - fun realtimeUrl(realtimeUrl: Optional) = realtimeUrl(realtimeUrl.getOrNull()) + /** + * Returns the raw JSON value of [proxyUrl]. + * + * Unlike [proxyUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("proxy_url") @ExcludeMissing fun _proxyUrl(): JsonField = proxyUrl /** - * Sets [Builder.realtimeUrl] to an arbitrary JSON value. + * Returns the raw JSON value of [realtimeUrl]. * - * You should usually call [Builder.realtimeUrl] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [realtimeUrl], this method doesn't throw if the JSON field has an unexpected type. */ - fun realtimeUrl(realtimeUrl: JsonField) = apply { body.realtimeUrl(realtimeUrl) } + @JsonProperty("realtime_url") + @ExcludeMissing + fun _realtimeUrl(): JsonField = realtimeUrl - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) - } + fun toBuilder() = Builder().from(this) - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + companion object { - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() } - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** A builder for [Body]. */ + class Builder internal constructor() { - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + private var apiUrl: JsonField = JsonMissing.of() + private var isUniversalApi: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var proxyUrl: JsonField = JsonMissing.of() + private var realtimeUrl: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + @JvmSynthetic + internal fun from(body: Body) = apply { + apiUrl = body.apiUrl + isUniversalApi = body.isUniversalApi + name = body.name + proxyUrl = body.proxyUrl + realtimeUrl = body.realtimeUrl + additionalProperties = body.additionalProperties.toMutableMap() + } - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + fun apiUrl(apiUrl: String?) = apiUrl(JsonField.ofNullable(apiUrl)) - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.apiUrl] with `apiUrl.orElse(null)`. */ + fun apiUrl(apiUrl: Optional) = apiUrl(apiUrl.getOrNull()) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Sets [Builder.apiUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.apiUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun apiUrl(apiUrl: JsonField) = apply { this.apiUrl = apiUrl } - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + fun isUniversalApi(isUniversalApi: Boolean?) = + isUniversalApi(JsonField.ofNullable(isUniversalApi)) - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** + * Alias for [Builder.isUniversalApi]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun isUniversalApi(isUniversalApi: Boolean) = isUniversalApi(isUniversalApi as Boolean?) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.isUniversalApi] with `isUniversalApi.orElse(null)`. */ + fun isUniversalApi(isUniversalApi: Optional) = + isUniversalApi(isUniversalApi.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.isUniversalApi] to an arbitrary JSON value. + * + * You should usually call [Builder.isUniversalApi] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isUniversalApi(isUniversalApi: JsonField) = apply { + this.isUniversalApi = isUniversalApi + } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + /** Name of the organization */ + fun name(name: String?) = name(JsonField.ofNullable(name)) - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** + * 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 additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun proxyUrl(proxyUrl: String?) = proxyUrl(JsonField.ofNullable(proxyUrl)) - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + /** Alias for calling [Builder.proxyUrl] with `proxyUrl.orElse(null)`. */ + fun proxyUrl(proxyUrl: Optional) = proxyUrl(proxyUrl.getOrNull()) - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + /** + * Sets [Builder.proxyUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.proxyUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun proxyUrl(proxyUrl: JsonField) = apply { this.proxyUrl = proxyUrl } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + fun realtimeUrl(realtimeUrl: String?) = realtimeUrl(JsonField.ofNullable(realtimeUrl)) - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + /** Alias for calling [Builder.realtimeUrl] with `realtimeUrl.orElse(null)`. */ + fun realtimeUrl(realtimeUrl: Optional) = realtimeUrl(realtimeUrl.getOrNull()) + + /** + * Sets [Builder.realtimeUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.realtimeUrl] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun realtimeUrl(realtimeUrl: JsonField) = apply { + this.realtimeUrl = realtimeUrl } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body( + apiUrl, + isUniversalApi, + name, + proxyUrl, + realtimeUrl, + additionalProperties.toMutableMap(), + ) + } - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + apiUrl() + isUniversalApi() + name() + proxyUrl() + realtimeUrl() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + /** - * Returns an immutable instance of [OrganizationUpdateParams]. + * 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. - * - * The following fields are required: - * ```java - * .organizationId() - * ``` - * - * @throws IllegalStateException if any required field is unset. + * Used for best match union deserialization. */ - fun build(): OrganizationUpdateParams = - OrganizationUpdateParams( - checkRequired("organizationId", organizationId), - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + @JvmSynthetic + internal fun validity(): Int = + (if (apiUrl.asKnown().isPresent) 1 else 0) + + (if (isUniversalApi.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (proxyUrl.asKnown().isPresent) 1 else 0) + + (if (realtimeUrl.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && apiUrl == other.apiUrl && isUniversalApi == other.isUniversalApi && name == other.name && proxyUrl == other.proxyUrl && realtimeUrl == other.realtimeUrl && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(apiUrl, isUniversalApi, name, proxyUrl, realtimeUrl, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{apiUrl=$apiUrl, isUniversalApi=$isUniversalApi, name=$name, proxyUrl=$proxyUrl, realtimeUrl=$realtimeUrl, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PatchOrganizationMembersOutput.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PatchOrganizationMembersOutput.kt index 7a4c2743..03a43cc2 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PatchOrganizationMembersOutput.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PatchOrganizationMembersOutput.kt @@ -7,33 +7,34 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 -@NoAutoDetect class PatchOrganizationMembersOutput -@JsonCreator private constructor( - @JsonProperty("org_id") @ExcludeMissing private val orgId: JsonField = JsonMissing.of(), - @JsonProperty("status") - @ExcludeMissing - private val status: JsonField = JsonMissing.of(), - @JsonProperty("send_email_error") - @ExcludeMissing - private val sendEmailError: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val orgId: JsonField, + private val status: JsonField, + private val sendEmailError: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("org_id") @ExcludeMissing orgId: JsonField = JsonMissing.of(), + @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), + @JsonProperty("send_email_error") + @ExcludeMissing + sendEmailError: JsonField = JsonMissing.of(), + ) : this(orgId, status, sendEmailError, mutableMapOf()) + /** * The id of the org that was modified. * @@ -55,8 +56,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun sendEmailError(): Optional = - Optional.ofNullable(sendEmailError.getNullable("send_email_error")) + fun sendEmailError(): Optional = sendEmailError.getOptional("send_email_error") /** * Returns the raw JSON value of [orgId]. @@ -81,22 +81,15 @@ private constructor( @ExcludeMissing fun _sendEmailError(): JsonField = sendEmailError + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PatchOrganizationMembersOutput = apply { - if (validated) { - return@apply - } - - orgId() - status() - sendEmailError() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -212,10 +205,42 @@ private constructor( checkRequired("orgId", orgId), checkRequired("status", status), sendEmailError, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): PatchOrganizationMembersOutput = apply { + if (validated) { + return@apply + } + + orgId() + status().validate() + sendEmailError() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (orgId.asKnown().isPresent) 1 else 0) + + (status.asKnown().getOrNull()?.validity() ?: 0) + + (if (sendEmailError.asKnown().isPresent) 1 else 0) + class Status @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -297,6 +322,33 @@ private constructor( BraintrustInvalidDataException("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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Permission.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Permission.kt index 7b884f8d..7e4cb415 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Permission.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Permission.kt @@ -132,6 +132,32 @@ class Permission @JsonCreator private constructor(private val value: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("org_id") @ExcludeMissing private val orgId: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("deleted_at") - @ExcludeMissing - private val deletedAt: JsonField = JsonMissing.of(), - @JsonProperty("settings") - @ExcludeMissing - private val settings: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val name: JsonField, + private val orgId: JsonField, + private val created: JsonField, + private val deletedAt: JsonField, + private val settings: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("org_id") @ExcludeMissing orgId: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("deleted_at") + @ExcludeMissing + deletedAt: JsonField = JsonMissing.of(), + @JsonProperty("settings") + @ExcludeMissing + settings: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this(id, name, orgId, created, deletedAt, settings, userId, mutableMapOf()) + /** * Unique identifier for the project * @@ -72,7 +77,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Date of project deletion, or null if the project is still active @@ -80,15 +85,13 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun deletedAt(): Optional = - Optional.ofNullable(deletedAt.getNullable("deleted_at")) + fun deletedAt(): Optional = deletedAt.getOptional("deleted_at") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun settings(): Optional = - Optional.ofNullable(settings.getNullable("settings")) + fun settings(): Optional = settings.getOptional("settings") /** * Identifies the user who created the project @@ -96,7 +99,7 @@ private constructor( * @throws BraintrustInvalidDataException 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 [id]. @@ -149,26 +152,15 @@ private constructor( */ @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 = additionalProperties - - private var validated: Boolean = false - - fun validate(): Project = apply { - if (validated) { - return@apply - } - - id() - name() - orgId() - created() - deletedAt() - settings().ifPresent { it.validate() } - userId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -344,10 +336,50 @@ private constructor( deletedAt, settings, userId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Project = apply { + if (validated) { + return@apply + } + + id() + name() + orgId() + created() + deletedAt() + settings().ifPresent { it.validate() } + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (orgId.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (deletedAt.asKnown().isPresent) 1 else 0) + + (settings.asKnown().getOrNull()?.validity() ?: 0) + + (if (userId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectCreateParams.kt index 25f67ec7..f09b95b2 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectCreateParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -71,187 +69,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("org_name") - @ExcludeMissing - private val orgName: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * Name of the project - * - * @throws BraintrustInvalidDataException 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") - - /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the project belongs in. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun orgName(): Optional = Optional.ofNullable(orgName.getNullable("org_name")) - - /** - * 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 [orgName]. - * - * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - name() - orgName() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var name: JsonField? = null - private var orgName: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - orgName = body.orgName - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** Name of the project */ - 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 } - - /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the project belongs in. - */ - fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) - - /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ - fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) - - /** - * Sets [Builder.orgName] to an arbitrary JSON value. - * - * You should usually call [Builder.orgName] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun orgName(orgName: JsonField) = apply { this.orgName = orgName } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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 - * .name() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body(checkRequired("name", name), orgName, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && name == other.name && orgName == other.orgName && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, orgName, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{name=$name, orgName=$orgName, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -268,7 +85,6 @@ private constructor( } /** A builder for [ProjectCreateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -282,6 +98,16 @@ private constructor( additionalQueryParams = projectCreateParams.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: + * - [name] + * - [orgName] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** Name of the project */ fun name(name: String) = apply { body.name(name) } @@ -448,6 +274,210 @@ private constructor( ) } + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val name: JsonField, + private val orgName: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("org_name") @ExcludeMissing orgName: JsonField = JsonMissing.of(), + ) : this(name, orgName, mutableMapOf()) + + /** + * Name of the project + * + * @throws BraintrustInvalidDataException 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") + + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the project belongs in. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun orgName(): Optional = orgName.getOptional("org_name") + + /** + * 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 [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName + + @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 + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var orgName: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + orgName = body.orgName + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the project */ + 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 } + + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the project belongs in. + */ + fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** + * Sets [Builder.orgName] to an arbitrary JSON value. + * + * You should usually call [Builder.orgName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun orgName(orgName: JsonField) = apply { this.orgName = orgName } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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 + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body(checkRequired("name", name), orgName, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + orgName() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + (if (orgName.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && name == other.name && orgName == other.orgName && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, orgName, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, orgName=$orgName, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectDeleteParams.kt index d5ac8442..1da020c8 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectDeleteParams.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,26 +23,11 @@ private constructor( /** Project id */ fun projectId(): String = projectId - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectId - else -> "" - } - } + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -61,7 +45,6 @@ private constructor( } /** A builder for [ProjectDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var projectId: String? = null @@ -221,6 +204,19 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListPage.kt index 1d934cf4..0ed7293d 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListPage.kt @@ -2,167 +2,115 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.ProjectService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all projects. The projects are sorted by creation date, with the most recently-created - * projects coming first - */ +/** @see [ProjectService.list] */ class ProjectListPage private constructor( - private val projectsService: ProjectService, + private val service: ProjectService, private val params: ProjectListParams, - private val response: Response, + private val response: ProjectListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [ProjectListPageResponse], but gracefully handles missing data. + * + * @see [ProjectListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ProjectListPage && projectsService == other.projectsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(projectsService, params, response) /* spotless:on */ - - override fun toString() = - "ProjectListPage{projectsService=$projectsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - ProjectListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - ProjectListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { projectsService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(projectsService: ProjectService, params: ProjectListParams, response: Response) = - ProjectListPage(projectsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): ProjectListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): ProjectListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [ProjectListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [ProjectListPage]. */ + class Builder internal constructor() { - companion object { + private var service: ProjectService? = null + private var params: ProjectListParams? = null + private var response: ProjectListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [ProjectListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(projectListPage: ProjectListPage) = apply { + service = projectListPage.service + params = projectListPage.params + response = projectListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: ProjectService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: ProjectListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ProjectListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ProjectListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectListPage = + ProjectListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: ProjectListPage) : Iterable { @@ -183,4 +131,17 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ProjectListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "ProjectListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListPageAsync.kt index f206043f..3051a64a 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListPageAsync.kt @@ -2,172 +2,119 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.ProjectServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all projects. The projects are sorted by creation date, with the most recently-created - * projects coming first - */ +/** @see [ProjectServiceAsync.list] */ class ProjectListPageAsync private constructor( - private val projectsService: ProjectServiceAsync, + private val service: ProjectServiceAsync, private val params: ProjectListParams, - private val response: Response, + private val response: ProjectListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [ProjectListPageResponse], but gracefully handles missing data. + * + * @see [ProjectListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ProjectListPageAsync && projectsService == other.projectsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(projectsService, params, response) /* spotless:on */ - - override fun toString() = - "ProjectListPageAsync{projectsService=$projectsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - ProjectListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - ProjectListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { projectsService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of( - projectsService: ProjectServiceAsync, - params: ProjectListParams, - response: Response, - ) = ProjectListPageAsync(projectsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): ProjectListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): ProjectListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [ProjectListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [ProjectListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: ProjectServiceAsync? = null + private var params: ProjectListParams? = null + private var response: ProjectListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [ProjectListPageAsync]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(projectListPageAsync: ProjectListPageAsync) = apply { + service = projectListPageAsync.service + params = projectListPageAsync.params + response = projectListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: ProjectServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: ProjectListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ProjectListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ProjectListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectListPageAsync = + ProjectListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: ProjectListPageAsync) { @@ -195,4 +142,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ProjectListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "ProjectListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListPageResponse.kt new file mode 100644 index 00000000..b789cd90 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListPageResponse.kt @@ -0,0 +1,194 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class ProjectListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") + @ExcludeMissing + objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of project objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [ProjectListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(projectListPageResponse: ProjectListPageResponse) = apply { + objects = projectListPageResponse.objects.map { it.toMutableList() } + additionalProperties = projectListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of project objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [Project] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: Project) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ProjectListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectListPageResponse = + ProjectListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ProjectListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ProjectListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProjectListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListParams.kt index 6b30061c..75beee12 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListParams.kt @@ -2,22 +2,10 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -75,31 +63,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - endingBefore?.let { put("ending_before", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - orgName?.let { put("org_name", it) } - projectName?.let { put("project_name", it) } - startingAfter?.let { put("starting_after", it) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -111,7 +74,6 @@ private constructor( } /** A builder for [ProjectListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var endingBefore: String? = null @@ -316,17 +278,39 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + endingBefore?.let { put("ending_before", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + orgName?.let { put("org_name", it) } + projectName?.let { put("project_name", it) } + startingAfter?.let { put("starting_after", it) } + putAll(additionalQueryParams) + } + .build() + /** * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -341,15 +325,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -365,7 +346,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -382,51 +362,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFeedbackParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFeedbackParams.kt index 13ea4533..e8cac1f5 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFeedbackParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFeedbackParams.kt @@ -6,20 +6,20 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 kotlin.jvm.optionals.getOrNull /** Log feedback for a set of project logs events */ class ProjectLogFeedbackParams @@ -54,171 +54,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectId - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("feedback") - @ExcludeMissing - private val feedback: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * A list of project logs feedback items - * - * @throws BraintrustInvalidDataException 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 feedback(): List = feedback.getRequired("feedback") - - /** - * Returns the raw JSON value of [feedback]. - * - * Unlike [feedback], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("feedback") - @ExcludeMissing - fun _feedback(): JsonField> = feedback - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - feedback().forEach { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .feedback() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var feedback: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - feedback = body.feedback.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** A list of project logs feedback items */ - fun feedback(feedback: List) = feedback(JsonField.of(feedback)) - - /** - * Sets [Builder.feedback] to an arbitrary JSON value. - * - * You should usually call [Builder.feedback] with a well-typed - * `List` value instead. This method is primarily for setting - * the field to an undocumented or not yet supported value. - */ - fun feedback(feedback: JsonField>) = apply { - this.feedback = feedback.map { it.toMutableList() } - } - - /** - * Adds a single [FeedbackProjectLogsItem] to [Builder.feedback]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addFeedback(feedback: FeedbackProjectLogsItem) = apply { - this.feedback = - (this.feedback ?: JsonField.of(mutableListOf())).also { - checkKnown("feedback", it).add(feedback) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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 - * .feedback() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("feedback", feedback).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && feedback == other.feedback && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(feedback, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{feedback=$feedback, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -236,7 +71,6 @@ private constructor( } /** A builder for [ProjectLogFeedbackParams]. */ - @NoAutoDetect class Builder internal constructor() { private var projectId: String? = null @@ -255,6 +89,15 @@ private constructor( /** Project id */ fun projectId(projectId: String) = apply { this.projectId = projectId } + /** + * 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: + * - [feedback] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** A list of project logs feedback items */ fun feedback(feedback: List) = apply { body.feedback(feedback) } @@ -415,6 +258,196 @@ private constructor( ) } + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val feedback: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("feedback") + @ExcludeMissing + feedback: JsonField> = JsonMissing.of() + ) : this(feedback, mutableMapOf()) + + /** + * A list of project logs feedback items + * + * @throws BraintrustInvalidDataException 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 feedback(): List = feedback.getRequired("feedback") + + /** + * Returns the raw JSON value of [feedback]. + * + * Unlike [feedback], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("feedback") + @ExcludeMissing + fun _feedback(): JsonField> = feedback + + @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 + * .feedback() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var feedback: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + feedback = body.feedback.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** A list of project logs feedback items */ + fun feedback(feedback: List) = feedback(JsonField.of(feedback)) + + /** + * Sets [Builder.feedback] to an arbitrary JSON value. + * + * You should usually call [Builder.feedback] with a well-typed + * `List` value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun feedback(feedback: JsonField>) = apply { + this.feedback = feedback.map { it.toMutableList() } + } + + /** + * Adds a single [FeedbackProjectLogsItem] to [Builder.feedback]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFeedback(feedback: FeedbackProjectLogsItem) = apply { + this.feedback = + (this.feedback ?: JsonField.of(mutableListOf())).also { + checkKnown("feedback", it).add(feedback) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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 + * .feedback() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("feedback", feedback).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + feedback().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (feedback.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && feedback == other.feedback && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(feedback, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{feedback=$feedback, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFetchParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFetchParams.kt index a3629afc..3b8204f5 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFetchParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFetchParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -86,26 +85,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - limit?.let { put("limit", it.toString()) } - maxRootSpanId?.let { put("max_root_span_id", it) } - maxXactId?.let { put("max_xact_id", it) } - version?.let { put("version", it) } - putAll(additionalQueryParams) - } - .build() - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -122,7 +101,6 @@ private constructor( } /** A builder for [ProjectLogFetchParams]. */ - @NoAutoDetect class Builder internal constructor() { private var projectId: String? = null @@ -342,6 +320,25 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + limit?.let { put("limit", it.toString()) } + maxRootSpanId?.let { put("max_root_span_id", it) } + maxXactId?.let { put("max_xact_id", it) } + version?.let { put("version", it) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFetchPostParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFetchPostParams.kt index 6b1ffba5..31b5a074 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFetchPostParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFetchPostParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -154,41 +152,53 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) - override fun _headers(): Headers = additionalHeaders + companion object { - override fun _queryParams(): QueryParams = additionalQueryParams + /** + * Returns a mutable builder for constructing an instance of [ProjectLogFetchPostParams]. + * + * The following fields are required: + * ```java + * .projectId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectId - else -> "" + /** A builder for [ProjectLogFetchPostParams]. */ + class Builder internal constructor() { + + private var projectId: 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(projectLogFetchPostParams: ProjectLogFetchPostParams) = apply { + projectId = projectLogFetchPostParams.projectId + body = projectLogFetchPostParams.body.toBuilder() + additionalHeaders = projectLogFetchPostParams.additionalHeaders.toBuilder() + additionalQueryParams = projectLogFetchPostParams.additionalQueryParams.toBuilder() } - } - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("cursor") - @ExcludeMissing - private val cursor: JsonField = JsonMissing.of(), - @JsonProperty("limit") - @ExcludeMissing - private val limit: JsonField = JsonMissing.of(), - @JsonProperty("max_root_span_id") - @ExcludeMissing - private val maxRootSpanId: JsonField = JsonMissing.of(), - @JsonProperty("max_xact_id") - @ExcludeMissing - private val maxXactId: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** Project id */ + fun projectId(projectId: String) = apply { this.projectId = projectId } + + /** + * 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: + * - [cursor] + * - [limit] + * - [maxRootSpanId] + * - [maxXactId] + * - [version] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } /** * An opaque string to be used as a cursor for the next page of results, in order from @@ -196,11 +206,19 @@ private constructor( * * The string can be obtained directly from the `cursor` property of the previous fetch * query + */ + fun cursor(cursor: String?) = apply { body.cursor(cursor) } + + /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ + fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) + + /** + * Sets [Builder.cursor] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.cursor] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - fun cursor(): Optional = Optional.ofNullable(cursor.getNullable("cursor")) + fun cursor(cursor: JsonField) = apply { body.cursor(cursor) } /** * limit the number of traces fetched @@ -216,11 +234,26 @@ private constructor( * The `limit` parameter controls the number of full traces to return. So you may end up * with more individual rows than the specified limit if you are fetching events containing * traces. + */ + fun limit(limit: Long?) = apply { body.limit(limit) } + + /** + * Alias for [Builder.limit]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * This unboxed primitive overload exists for backwards compatibility. + */ + fun limit(limit: Long) = limit(limit as Long?) + + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) + + /** + * Sets [Builder.limit] to an arbitrary JSON value. + * + * You should usually call [Builder.limit] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - fun limit(): Optional = Optional.ofNullable(limit.getNullable("limit")) + fun limit(limit: JsonField) = apply { body.limit(limit) } /** * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor of @@ -233,12 +266,23 @@ private constructor( * cursor for the next page can be found as the row with the minimum (earliest) value of the * tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an overview of * paginating fetch queries. + */ + fun maxRootSpanId(maxRootSpanId: String?) = apply { body.maxRootSpanId(maxRootSpanId) } + + /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ + fun maxRootSpanId(maxRootSpanId: Optional) = + maxRootSpanId(maxRootSpanId.getOrNull()) + + /** + * Sets [Builder.maxRootSpanId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.maxRootSpanId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun maxRootSpanId(): Optional = - Optional.ofNullable(maxRootSpanId.getNullable("max_root_span_id")) + fun maxRootSpanId(maxRootSpanId: JsonField) = apply { + body.maxRootSpanId(maxRootSpanId) + } /** * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor of @@ -251,330 +295,212 @@ private constructor( * cursor for the next page can be found as the row with the minimum (earliest) value of the * tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an overview of * paginating fetch queries. + */ + fun maxXactId(maxXactId: String?) = apply { body.maxXactId(maxXactId) } + + /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ + fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) + + /** + * Sets [Builder.maxXactId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.maxXactId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun maxXactId(): Optional = - Optional.ofNullable(maxXactId.getNullable("max_xact_id")) + fun maxXactId(maxXactId: JsonField) = apply { body.maxXactId(maxXactId) } /** * Retrieve a snapshot of events from a past time * * The version id is essentially a filter on the latest event transaction id. You can use * the `max_xact_id` returned by a past fetch as the version to reproduce that exact fetch. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). */ - fun version(): Optional = Optional.ofNullable(version.getNullable("version")) + fun version(version: String?) = apply { body.version(version) } - /** - * Returns the raw JSON value of [cursor]. - * - * Unlike [cursor], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("cursor") @ExcludeMissing fun _cursor(): JsonField = cursor + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) /** - * Returns the raw JSON value of [limit]. + * Sets [Builder.version] to an arbitrary JSON value. * - * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.version] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit + fun version(version: JsonField) = apply { body.version(version) } - /** - * Returns the raw JSON value of [maxRootSpanId]. - * - * Unlike [maxRootSpanId], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("max_root_span_id") - @ExcludeMissing - fun _maxRootSpanId(): JsonField = maxRootSpanId + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - /** - * Returns the raw JSON value of [maxXactId]. - * - * Unlike [maxXactId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("max_xact_id") @ExcludeMissing fun _maxXactId(): JsonField = maxXactId + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - /** - * Returns the raw JSON value of [version]. - * - * Unlike [version], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - private var validated: Boolean = false + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - fun validate(): Body = apply { - if (validated) { - return@apply - } + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - cursor() - limit() - maxRootSpanId() - maxXactId() - version() - validated = true + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun toBuilder() = Builder().from(this) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - companion object { + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** Returns a mutable builder for constructing an instance of [Body]. */ - @JvmStatic fun builder() = Builder() + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - private var cursor: JsonField = JsonMissing.of() - private var limit: JsonField = JsonMissing.of() - private var maxRootSpanId: JsonField = JsonMissing.of() - private var maxXactId: JsonField = JsonMissing.of() - private var version: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - @JvmSynthetic - internal fun from(body: Body) = apply { - cursor = body.cursor - limit = body.limit - maxRootSpanId = body.maxRootSpanId - maxXactId = body.maxXactId - version = body.version - additionalProperties = body.additionalProperties.toMutableMap() - } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** - * An opaque string to be used as a cursor for the next page of results, in order from - * latest to earliest. - * - * The string can be obtained directly from the `cursor` property of the previous fetch - * query - */ - fun cursor(cursor: String?) = cursor(JsonField.ofNullable(cursor)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ - fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.cursor] to an arbitrary JSON value. - * - * You should usually call [Builder.cursor] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun cursor(cursor: JsonField) = apply { this.cursor = cursor } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - /** - * limit the number of traces fetched - * - * Fetch queries may be paginated if the total result size is expected to be large (e.g. - * project_logs which accumulate over a long time). Note that fetch queries only support - * pagination in descending time order (from latest to earliest `_xact_id`. Furthermore, - * later pages may return rows which showed up in earlier pages, except with an earlier - * `_xact_id`. This happens because pagination occurs over the whole version history of - * the event log. You will most likely want to exclude any such duplicate, outdated rows - * (by `id`) from your combined result set. - * - * The `limit` parameter controls the number of full traces to return. So you may end up - * with more individual rows than the specified limit if you are fetching events - * containing traces. - */ - fun limit(limit: Long?) = limit(JsonField.ofNullable(limit)) - - /** - * Alias for [Builder.limit]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun limit(limit: Long) = limit(limit as Long?) - - /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ - fun limit(limit: Optional) = limit(limit.getOrNull()) - - /** - * Sets [Builder.limit] to an arbitrary JSON value. - * - * You should usually call [Builder.limit] with a well-typed [Long] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun limit(limit: JsonField) = apply { this.limit = limit } - - /** - * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor - * of the explicit 'cursor' returned by object fetch requests. Please prefer the - * 'cursor' argument going forwards. - * - * Together, `max_xact_id` and `max_root_span_id` form a pagination cursor - * - * Since a paginated fetch query returns results in order from latest to earliest, the - * cursor for the next page can be found as the row with the minimum (earliest) value of - * the tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an - * overview of paginating fetch queries. - */ - fun maxRootSpanId(maxRootSpanId: String?) = - maxRootSpanId(JsonField.ofNullable(maxRootSpanId)) - - /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ - fun maxRootSpanId(maxRootSpanId: Optional) = - maxRootSpanId(maxRootSpanId.getOrNull()) - - /** - * Sets [Builder.maxRootSpanId] to an arbitrary JSON value. - * - * You should usually call [Builder.maxRootSpanId] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun maxRootSpanId(maxRootSpanId: JsonField) = apply { - this.maxRootSpanId = maxRootSpanId - } - - /** - * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor - * of the explicit 'cursor' returned by object fetch requests. Please prefer the - * 'cursor' argument going forwards. - * - * Together, `max_xact_id` and `max_root_span_id` form a pagination cursor - * - * Since a paginated fetch query returns results in order from latest to earliest, the - * cursor for the next page can be found as the row with the minimum (earliest) value of - * the tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an - * overview of paginating fetch queries. - */ - fun maxXactId(maxXactId: String?) = maxXactId(JsonField.ofNullable(maxXactId)) - - /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ - fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) - - /** - * Sets [Builder.maxXactId] to an arbitrary JSON value. - * - * You should usually call [Builder.maxXactId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun maxXactId(maxXactId: JsonField) = apply { this.maxXactId = maxXactId } - - /** - * Retrieve a snapshot of events from a past time - * - * The version id is essentially a filter on the latest event transaction id. You can - * use the `max_xact_id` returned by a past fetch as the version to reproduce that exact - * fetch. - */ - fun version(version: String?) = version(JsonField.ofNullable(version)) - - /** Alias for calling [Builder.version] with `version.orElse(null)`. */ - fun version(version: Optional) = version(version.getOrNull()) - - /** - * Sets [Builder.version] to an arbitrary JSON value. - * - * You should usually call [Builder.version] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun version(version: JsonField) = apply { this.version = version } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Body = - Body( - cursor, - limit, - maxRootSpanId, - maxXactId, - version, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && cursor == other.cursor && limit == other.limit && maxRootSpanId == other.maxRootSpanId && maxXactId == other.maxXactId && version == other.version && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(cursor, limit, maxRootSpanId, maxXactId, version, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{cursor=$cursor, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [ProjectLogFetchPostParams]. + * Returns an immutable instance of [ProjectLogFetchPostParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java * .projectId() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): ProjectLogFetchPostParams = + ProjectLogFetchPostParams( + checkRequired("projectId", projectId), + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [ProjectLogFetchPostParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var projectId: String? = null - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + fun _body(): Body = body - @JvmSynthetic - internal fun from(projectLogFetchPostParams: ProjectLogFetchPostParams) = apply { - projectId = projectLogFetchPostParams.projectId - body = projectLogFetchPostParams.body.toBuilder() - additionalHeaders = projectLogFetchPostParams.additionalHeaders.toBuilder() - additionalQueryParams = projectLogFetchPostParams.additionalQueryParams.toBuilder() + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectId + else -> "" } - /** Project id */ - fun projectId(projectId: String) = apply { this.projectId = projectId } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val cursor: JsonField, + private val limit: JsonField, + private val maxRootSpanId: JsonField, + private val maxXactId: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("cursor") @ExcludeMissing cursor: JsonField = JsonMissing.of(), + @JsonProperty("limit") @ExcludeMissing limit: JsonField = JsonMissing.of(), + @JsonProperty("max_root_span_id") + @ExcludeMissing + maxRootSpanId: JsonField = JsonMissing.of(), + @JsonProperty("max_xact_id") + @ExcludeMissing + maxXactId: JsonField = JsonMissing.of(), + @JsonProperty("version") @ExcludeMissing version: JsonField = JsonMissing.of(), + ) : this(cursor, limit, maxRootSpanId, maxXactId, version, mutableMapOf()) /** * An opaque string to be used as a cursor for the next page of results, in order from @@ -582,19 +508,11 @@ private constructor( * * The string can be obtained directly from the `cursor` property of the previous fetch * query - */ - fun cursor(cursor: String?) = apply { body.cursor(cursor) } - - /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ - fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) - - /** - * Sets [Builder.cursor] to an arbitrary JSON value. * - * You should usually call [Builder.cursor] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun cursor(cursor: JsonField) = apply { body.cursor(cursor) } + fun cursor(): Optional = cursor.getOptional("cursor") /** * limit the number of traces fetched @@ -610,26 +528,11 @@ private constructor( * The `limit` parameter controls the number of full traces to return. So you may end up * with more individual rows than the specified limit if you are fetching events containing * traces. - */ - fun limit(limit: Long?) = apply { body.limit(limit) } - - /** - * Alias for [Builder.limit]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun limit(limit: Long) = limit(limit as Long?) - - /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ - fun limit(limit: Optional) = limit(limit.getOrNull()) - - /** - * Sets [Builder.limit] to an arbitrary JSON value. * - * You should usually call [Builder.limit] with a well-typed [Long] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun limit(limit: JsonField) = apply { body.limit(limit) } + fun limit(): Optional = limit.getOptional("limit") /** * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor of @@ -642,23 +545,11 @@ private constructor( * cursor for the next page can be found as the row with the minimum (earliest) value of the * tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an overview of * paginating fetch queries. - */ - fun maxRootSpanId(maxRootSpanId: String?) = apply { body.maxRootSpanId(maxRootSpanId) } - - /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ - fun maxRootSpanId(maxRootSpanId: Optional) = - maxRootSpanId(maxRootSpanId.getOrNull()) - - /** - * Sets [Builder.maxRootSpanId] to an arbitrary JSON value. * - * You should usually call [Builder.maxRootSpanId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun maxRootSpanId(maxRootSpanId: JsonField) = apply { - body.maxRootSpanId(maxRootSpanId) - } + fun maxRootSpanId(): Optional = maxRootSpanId.getOptional("max_root_span_id") /** * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor of @@ -671,176 +562,321 @@ private constructor( * cursor for the next page can be found as the row with the minimum (earliest) value of the * tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an overview of * paginating fetch queries. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun maxXactId(maxXactId: String?) = apply { body.maxXactId(maxXactId) } + fun maxXactId(): Optional = maxXactId.getOptional("max_xact_id") - /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ - fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) + /** + * Retrieve a snapshot of events from a past time + * + * The version id is essentially a filter on the latest event transaction id. You can use + * the `max_xact_id` returned by a past fetch as the version to reproduce that exact fetch. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun version(): Optional = version.getOptional("version") /** - * Sets [Builder.maxXactId] to an arbitrary JSON value. + * Returns the raw JSON value of [cursor]. * - * You should usually call [Builder.maxXactId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [cursor], this method doesn't throw if the JSON field has an unexpected type. */ - fun maxXactId(maxXactId: JsonField) = apply { body.maxXactId(maxXactId) } + @JsonProperty("cursor") @ExcludeMissing fun _cursor(): JsonField = cursor /** - * Retrieve a snapshot of events from a past time + * Returns the raw JSON value of [limit]. * - * The version id is essentially a filter on the latest event transaction id. You can use - * the `max_xact_id` returned by a past fetch as the version to reproduce that exact fetch. + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. */ - fun version(version: String?) = apply { body.version(version) } + @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit - /** Alias for calling [Builder.version] with `version.orElse(null)`. */ - fun version(version: Optional) = version(version.getOrNull()) + /** + * Returns the raw JSON value of [maxRootSpanId]. + * + * Unlike [maxRootSpanId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("max_root_span_id") + @ExcludeMissing + fun _maxRootSpanId(): JsonField = maxRootSpanId /** - * Sets [Builder.version] to an arbitrary JSON value. + * Returns the raw JSON value of [maxXactId]. * - * You should usually call [Builder.version] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [maxXactId], this method doesn't throw if the JSON field has an unexpected type. */ - fun version(version: JsonField) = apply { body.version(version) } + @JsonProperty("max_xact_id") @ExcludeMissing fun _maxXactId(): JsonField = maxXactId - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) - } + /** + * Returns the raw JSON value of [version]. + * + * Unlike [version], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) - } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + fun toBuilder() = Builder().from(this) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + companion object { - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** A builder for [Body]. */ + class Builder internal constructor() { - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + private var cursor: JsonField = JsonMissing.of() + private var limit: JsonField = JsonMissing.of() + private var maxRootSpanId: JsonField = JsonMissing.of() + private var maxXactId: JsonField = JsonMissing.of() + private var version: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + @JvmSynthetic + internal fun from(body: Body) = apply { + cursor = body.cursor + limit = body.limit + maxRootSpanId = body.maxRootSpanId + maxXactId = body.maxXactId + version = body.version + additionalProperties = body.additionalProperties.toMutableMap() + } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * An opaque string to be used as a cursor for the next page of results, in order from + * latest to earliest. + * + * The string can be obtained directly from the `cursor` property of the previous fetch + * query + */ + fun cursor(cursor: String?) = cursor(JsonField.ofNullable(cursor)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ + fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.cursor] to an arbitrary JSON value. + * + * You should usually call [Builder.cursor] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun cursor(cursor: JsonField) = apply { this.cursor = cursor } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** + * limit the number of traces fetched + * + * Fetch queries may be paginated if the total result size is expected to be large (e.g. + * project_logs which accumulate over a long time). Note that fetch queries only support + * pagination in descending time order (from latest to earliest `_xact_id`. Furthermore, + * later pages may return rows which showed up in earlier pages, except with an earlier + * `_xact_id`. This happens because pagination occurs over the whole version history of + * the event log. You will most likely want to exclude any such duplicate, outdated rows + * (by `id`) from your combined result set. + * + * The `limit` parameter controls the number of full traces to return. So you may end up + * with more individual rows than the specified limit if you are fetching events + * containing traces. + */ + fun limit(limit: Long?) = limit(JsonField.ofNullable(limit)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun limit(limit: Long) = limit(limit as Long?) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + /** + * Sets [Builder.limit] to an arbitrary JSON value. + * + * You should usually call [Builder.limit] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun limit(limit: JsonField) = apply { this.limit = limit } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + /** + * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor + * of the explicit 'cursor' returned by object fetch requests. Please prefer the + * 'cursor' argument going forwards. + * + * Together, `max_xact_id` and `max_root_span_id` form a pagination cursor + * + * Since a paginated fetch query returns results in order from latest to earliest, the + * cursor for the next page can be found as the row with the minimum (earliest) value of + * the tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an + * overview of paginating fetch queries. + */ + fun maxRootSpanId(maxRootSpanId: String?) = + maxRootSpanId(JsonField.ofNullable(maxRootSpanId)) - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ + fun maxRootSpanId(maxRootSpanId: Optional) = + maxRootSpanId(maxRootSpanId.getOrNull()) - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** + * Sets [Builder.maxRootSpanId] to an arbitrary JSON value. + * + * You should usually call [Builder.maxRootSpanId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxRootSpanId(maxRootSpanId: JsonField) = apply { + this.maxRootSpanId = maxRootSpanId + } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + /** + * DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor + * of the explicit 'cursor' returned by object fetch requests. Please prefer the + * 'cursor' argument going forwards. + * + * Together, `max_xact_id` and `max_root_span_id` form a pagination cursor + * + * Since a paginated fetch query returns results in order from latest to earliest, the + * cursor for the next page can be found as the row with the minimum (earliest) value of + * the tuple `(_xact_id, root_span_id)`. See the documentation of `limit` for an + * overview of paginating fetch queries. + */ + fun maxXactId(maxXactId: String?) = maxXactId(JsonField.ofNullable(maxXactId)) - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ + fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + /** + * Sets [Builder.maxXactId] to an arbitrary JSON value. + * + * You should usually call [Builder.maxXactId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxXactId(maxXactId: JsonField) = apply { this.maxXactId = maxXactId } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + /** + * Retrieve a snapshot of events from a past time + * + * The version id is essentially a filter on the latest event transaction id. You can + * use the `max_xact_id` returned by a past fetch as the version to reproduce that exact + * fetch. + */ + fun version(version: String?) = version(JsonField.ofNullable(version)) + + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) + + /** + * Sets [Builder.version] to an arbitrary JSON value. + * + * You should usually call [Builder.version] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun version(version: JsonField) = apply { this.version = version } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body( + cursor, + limit, + maxRootSpanId, + maxXactId, + version, + additionalProperties.toMutableMap(), + ) + } - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + cursor() + limit() + maxRootSpanId() + maxXactId() + version() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + /** - * Returns an immutable instance of [ProjectLogFetchPostParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * The following fields are required: - * ```java - * .projectId() - * ``` - * - * @throws IllegalStateException if any required field is unset. + * Used for best match union deserialization. */ - fun build(): ProjectLogFetchPostParams = - ProjectLogFetchPostParams( - checkRequired("projectId", projectId), - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + @JvmSynthetic + internal fun validity(): Int = + (if (cursor.asKnown().isPresent) 1 else 0) + + (if (limit.asKnown().isPresent) 1 else 0) + + (if (maxRootSpanId.asKnown().isPresent) 1 else 0) + + (if (maxXactId.asKnown().isPresent) 1 else 0) + + (if (version.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && cursor == other.cursor && limit == other.limit && maxRootSpanId == other.maxRootSpanId && maxXactId == other.maxXactId && version == other.version && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(cursor, limit, maxRootSpanId, maxXactId, version, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{cursor=$cursor, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogInsertParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogInsertParams.kt index 629a3f65..8ea2f668 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogInsertParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogInsertParams.kt @@ -6,20 +6,20 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 kotlin.jvm.optionals.getOrNull /** Insert a set of events into the project logs */ class ProjectLogInsertParams @@ -54,170 +54,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectId - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("events") - @ExcludeMissing - private val events: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * A list of project logs events to insert - * - * @throws BraintrustInvalidDataException 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 events(): List = events.getRequired("events") - - /** - * Returns the raw JSON value of [events]. - * - * Unlike [events], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("events") - @ExcludeMissing - fun _events(): JsonField> = events - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - events().forEach { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .events() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var events: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - events = body.events.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** A list of project logs events to insert */ - fun events(events: List) = events(JsonField.of(events)) - - /** - * Sets [Builder.events] to an arbitrary JSON value. - * - * You should usually call [Builder.events] with a well-typed - * `List` value instead. This method is primarily for setting - * the field to an undocumented or not yet supported value. - */ - fun events(events: JsonField>) = apply { - this.events = events.map { it.toMutableList() } - } - - /** - * Adds a single [InsertProjectLogsEvent] to [events]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addEvent(event: InsertProjectLogsEvent) = apply { - events = - (events ?: JsonField.of(mutableListOf())).also { - checkKnown("events", it).add(event) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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 - * .events() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("events", events).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && events == other.events && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(events, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Body{events=$events, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -235,7 +71,6 @@ private constructor( } /** A builder for [ProjectLogInsertParams]. */ - @NoAutoDetect class Builder internal constructor() { private var projectId: String? = null @@ -254,6 +89,15 @@ private constructor( /** Project id */ fun projectId(projectId: String) = apply { this.projectId = projectId } + /** + * 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: + * - [events] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** A list of project logs events to insert */ fun events(events: List) = apply { body.events(events) } @@ -412,6 +256,195 @@ private constructor( ) } + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val events: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("events") + @ExcludeMissing + events: JsonField> = JsonMissing.of() + ) : this(events, mutableMapOf()) + + /** + * A list of project logs events to insert + * + * @throws BraintrustInvalidDataException 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 events(): List = events.getRequired("events") + + /** + * Returns the raw JSON value of [events]. + * + * Unlike [events], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("events") + @ExcludeMissing + fun _events(): JsonField> = events + + @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 + * .events() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var events: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + events = body.events.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** A list of project logs events to insert */ + fun events(events: List) = events(JsonField.of(events)) + + /** + * Sets [Builder.events] to an arbitrary JSON value. + * + * You should usually call [Builder.events] with a well-typed + * `List` value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun events(events: JsonField>) = apply { + this.events = events.map { it.toMutableList() } + } + + /** + * Adds a single [InsertProjectLogsEvent] to [events]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addEvent(event: InsertProjectLogsEvent) = apply { + events = + (events ?: JsonField.of(mutableListOf())).also { + checkKnown("events", it).add(event) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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 + * .events() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("events", events).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + events().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (events.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && events == other.events && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(events, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = "Body{events=$events, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogsEvent.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogsEvent.kt index f4371612..5d6dd53e 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogsEvent.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogsEvent.kt @@ -7,10 +7,8 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -18,66 +16,95 @@ import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class ProjectLogsEvent -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("_xact_id") - @ExcludeMissing - private val _xactId: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("log_id") @ExcludeMissing private val logId: JsonField = JsonMissing.of(), - @JsonProperty("org_id") @ExcludeMissing private val orgId: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("root_span_id") - @ExcludeMissing - private val rootSpanId: JsonField = JsonMissing.of(), - @JsonProperty("span_id") - @ExcludeMissing - private val spanId: JsonField = JsonMissing.of(), - @JsonProperty("context") - @ExcludeMissing - private val context: JsonField = JsonMissing.of(), - @JsonProperty("error") @ExcludeMissing private val error: JsonValue = JsonMissing.of(), - @JsonProperty("expected") @ExcludeMissing private val expected: JsonValue = JsonMissing.of(), - @JsonProperty("input") @ExcludeMissing private val input: JsonValue = JsonMissing.of(), - @JsonProperty("is_root") - @ExcludeMissing - private val isRoot: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("metrics") - @ExcludeMissing - private val metrics: JsonField = JsonMissing.of(), - @JsonProperty("origin") - @ExcludeMissing - private val origin: JsonField = JsonMissing.of(), - @JsonProperty("output") @ExcludeMissing private val output: JsonValue = JsonMissing.of(), - @JsonProperty("scores") - @ExcludeMissing - private val scores: JsonField = JsonMissing.of(), - @JsonProperty("span_attributes") - @ExcludeMissing - private val spanAttributes: JsonField = JsonMissing.of(), - @JsonProperty("span_parents") - @ExcludeMissing - private val spanParents: JsonField> = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val _xactId: JsonField, + private val created: JsonField, + private val logId: JsonField, + private val orgId: JsonField, + private val projectId: JsonField, + private val rootSpanId: JsonField, + private val spanId: JsonField, + private val context: JsonField, + private val error: JsonValue, + private val expected: JsonValue, + private val input: JsonValue, + private val isRoot: JsonField, + private val metadata: JsonField, + private val metrics: JsonField, + private val origin: JsonField, + private val output: JsonValue, + private val scores: JsonField, + private val spanAttributes: JsonField, + private val spanParents: JsonField>, + private val tags: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("_xact_id") @ExcludeMissing _xactId: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("log_id") @ExcludeMissing logId: JsonField = JsonMissing.of(), + @JsonProperty("org_id") @ExcludeMissing orgId: JsonField = JsonMissing.of(), + @JsonProperty("project_id") @ExcludeMissing projectId: JsonField = JsonMissing.of(), + @JsonProperty("root_span_id") + @ExcludeMissing + rootSpanId: JsonField = JsonMissing.of(), + @JsonProperty("span_id") @ExcludeMissing spanId: JsonField = JsonMissing.of(), + @JsonProperty("context") @ExcludeMissing context: JsonField = JsonMissing.of(), + @JsonProperty("error") @ExcludeMissing error: JsonValue = JsonMissing.of(), + @JsonProperty("expected") @ExcludeMissing expected: JsonValue = JsonMissing.of(), + @JsonProperty("input") @ExcludeMissing input: JsonValue = JsonMissing.of(), + @JsonProperty("is_root") @ExcludeMissing isRoot: JsonField = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("metrics") @ExcludeMissing metrics: JsonField = JsonMissing.of(), + @JsonProperty("origin") + @ExcludeMissing + origin: JsonField = JsonMissing.of(), + @JsonProperty("output") @ExcludeMissing output: JsonValue = JsonMissing.of(), + @JsonProperty("scores") @ExcludeMissing scores: JsonField = JsonMissing.of(), + @JsonProperty("span_attributes") + @ExcludeMissing + spanAttributes: JsonField = JsonMissing.of(), + @JsonProperty("span_parents") + @ExcludeMissing + spanParents: JsonField> = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this( + id, + _xactId, + created, + logId, + orgId, + projectId, + rootSpanId, + spanId, + context, + error, + expected, + input, + isRoot, + metadata, + metrics, + origin, + output, + scores, + spanAttributes, + spanParents, + tags, + mutableMapOf(), + ) + /** * A unique identifier for the project logs event. If you don't provide one, BrainTrust will * generate one for you @@ -155,7 +182,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun context(): Optional = Optional.ofNullable(context.getNullable("context")) + fun context(): Optional = context.getOptional("context") /** The error that occurred, if any. */ @JsonProperty("error") @ExcludeMissing fun _error(): JsonValue = error @@ -179,7 +206,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun isRoot(): Optional = Optional.ofNullable(isRoot.getNullable("is_root")) + fun isRoot(): Optional = isRoot.getOptional("is_root") /** * A dictionary with additional data about the test example, model outputs, or just about @@ -191,7 +218,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** * Metrics are numerical measurements tracking the execution of the code that produced the @@ -201,7 +228,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metrics(): Optional = Optional.ofNullable(metrics.getNullable("metrics")) + fun metrics(): Optional = metrics.getOptional("metrics") /** * Indicates the event was copied from another object. @@ -209,7 +236,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun origin(): Optional = Optional.ofNullable(origin.getNullable("origin")) + fun origin(): Optional = origin.getOptional("origin") /** * The output of your application, including post-processing (an arbitrary, JSON serializable @@ -232,7 +259,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun scores(): Optional = Optional.ofNullable(scores.getNullable("scores")) + fun scores(): Optional = scores.getOptional("scores") /** * Human-identifying attributes of the span, such as name, type, etc. @@ -240,8 +267,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spanAttributes(): Optional = - Optional.ofNullable(spanAttributes.getNullable("span_attributes")) + fun spanAttributes(): Optional = spanAttributes.getOptional("span_attributes") /** * An array of the parent `span_ids` of this project logs event. This should be empty for the @@ -250,8 +276,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spanParents(): Optional> = - Optional.ofNullable(spanParents.getNullable("span_parents")) + fun spanParents(): Optional> = spanParents.getOptional("span_parents") /** * A list of tags to log @@ -259,7 +284,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [id]. @@ -384,36 +409,15 @@ private constructor( */ @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ProjectLogsEvent = apply { - if (validated) { - return@apply - } - - id() - _xactId() - created() - logId() - orgId() - projectId() - rootSpanId() - spanId() - context().ifPresent { it.validate() } - isRoot() - metadata().ifPresent { it.validate() } - metrics().ifPresent { it.validate() } - origin().ifPresent { it.validate() } - scores().ifPresent { it.validate() } - spanAttributes().ifPresent { it.validate() } - spanParents() - tags() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -872,10 +876,70 @@ private constructor( spanAttributes, (spanParents ?: JsonMissing.of()).map { it.toImmutable() }, (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): ProjectLogsEvent = apply { + if (validated) { + return@apply + } + + id() + _xactId() + created() + logId().validate() + orgId() + projectId() + rootSpanId() + spanId() + context().ifPresent { it.validate() } + isRoot() + metadata().ifPresent { it.validate() } + metrics().ifPresent { it.validate() } + origin().ifPresent { it.validate() } + scores().ifPresent { it.validate() } + spanAttributes().ifPresent { it.validate() } + spanParents() + tags() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (_xactId.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (logId.asKnown().getOrNull()?.validity() ?: 0) + + (if (orgId.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (rootSpanId.asKnown().isPresent) 1 else 0) + + (if (spanId.asKnown().isPresent) 1 else 0) + + (context.asKnown().getOrNull()?.validity() ?: 0) + + (if (isRoot.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (metrics.asKnown().getOrNull()?.validity() ?: 0) + + (origin.asKnown().getOrNull()?.validity() ?: 0) + + (scores.asKnown().getOrNull()?.validity() ?: 0) + + (spanAttributes.asKnown().getOrNull()?.validity() ?: 0) + + (spanParents.asKnown().getOrNull()?.size ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + /** A literal 'g' which identifies the log as a project log */ class LogId @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -958,6 +1022,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): LogId = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -976,31 +1067,34 @@ private constructor( * essentially the textual counterpart to `metrics`. Use the `caller_*` attributes to track the * location in code which produced the project logs event */ - @NoAutoDetect class Context - @JsonCreator private constructor( - @JsonProperty("caller_filename") - @ExcludeMissing - private val callerFilename: JsonField = JsonMissing.of(), - @JsonProperty("caller_functionname") - @ExcludeMissing - private val callerFunctionname: JsonField = JsonMissing.of(), - @JsonProperty("caller_lineno") - @ExcludeMissing - private val callerLineno: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val callerFilename: JsonField, + private val callerFunctionname: JsonField, + private val callerLineno: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("caller_filename") + @ExcludeMissing + callerFilename: JsonField = JsonMissing.of(), + @JsonProperty("caller_functionname") + @ExcludeMissing + callerFunctionname: JsonField = JsonMissing.of(), + @JsonProperty("caller_lineno") + @ExcludeMissing + callerLineno: JsonField = JsonMissing.of(), + ) : this(callerFilename, callerFunctionname, callerLineno, mutableMapOf()) + /** * Name of the file in code where the project logs event was created * * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun callerFilename(): Optional = - Optional.ofNullable(callerFilename.getNullable("caller_filename")) + fun callerFilename(): Optional = callerFilename.getOptional("caller_filename") /** * The function in code which created the project logs event @@ -1009,7 +1103,7 @@ private constructor( * the server responded with an unexpected value). */ fun callerFunctionname(): Optional = - Optional.ofNullable(callerFunctionname.getNullable("caller_functionname")) + callerFunctionname.getOptional("caller_functionname") /** * Line of code where the project logs event was created @@ -1017,8 +1111,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun callerLineno(): Optional = - Optional.ofNullable(callerLineno.getNullable("caller_lineno")) + fun callerLineno(): Optional = callerLineno.getOptional("caller_lineno") /** * Returns the raw JSON value of [callerFilename]. @@ -1050,22 +1143,15 @@ private constructor( @ExcludeMissing fun _callerLineno(): JsonField = callerLineno + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Context = apply { - if (validated) { - return@apply - } - - callerFilename() - callerFunctionname() - callerLineno() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1185,10 +1271,43 @@ private constructor( callerFilename, callerFunctionname, callerLineno, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Context = apply { + if (validated) { + return@apply + } + + callerFilename() + callerFunctionname() + callerLineno() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (callerFilename.asKnown().isPresent) 1 else 0) + + (if (callerFunctionname.asKnown().isPresent) 1 else 0) + + (if (callerLineno.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1214,24 +1333,24 @@ private constructor( * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys * must be strings */ - @NoAutoDetect class Metadata - @JsonCreator private constructor( - @JsonProperty("model") - @ExcludeMissing - private val model: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val model: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of() + ) : this(model, mutableMapOf()) + /** * The model used for this example * * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [model]. @@ -1240,20 +1359,15 @@ private constructor( */ @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - model() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1314,9 +1428,36 @@ private constructor( * * Further updates to this [Builder] will not mutate the returned instance. */ - fun build(): Metadata = Metadata(model, additionalProperties.toImmutable()) + fun build(): Metadata = Metadata(model, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + model() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1340,36 +1481,51 @@ private constructor( * project logs event. Use "start" and "end" to track the time span over which the project logs * event was produced */ - @NoAutoDetect class Metrics - @JsonCreator private constructor( - @JsonProperty("caller_filename") - @ExcludeMissing - private val callerFilename: JsonValue = JsonMissing.of(), - @JsonProperty("caller_functionname") - @ExcludeMissing - private val callerFunctionname: JsonValue = JsonMissing.of(), - @JsonProperty("caller_lineno") - @ExcludeMissing - private val callerLineno: JsonValue = JsonMissing.of(), - @JsonProperty("completion_tokens") - @ExcludeMissing - private val completionTokens: JsonField = JsonMissing.of(), - @JsonProperty("end") @ExcludeMissing private val end: JsonField = JsonMissing.of(), - @JsonProperty("prompt_tokens") - @ExcludeMissing - private val promptTokens: JsonField = JsonMissing.of(), - @JsonProperty("start") - @ExcludeMissing - private val start: JsonField = JsonMissing.of(), - @JsonProperty("tokens") - @ExcludeMissing - private val tokens: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val callerFilename: JsonValue, + private val callerFunctionname: JsonValue, + private val callerLineno: JsonValue, + private val completionTokens: JsonField, + private val end: JsonField, + private val promptTokens: JsonField, + private val start: JsonField, + private val tokens: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("caller_filename") + @ExcludeMissing + callerFilename: JsonValue = JsonMissing.of(), + @JsonProperty("caller_functionname") + @ExcludeMissing + callerFunctionname: JsonValue = JsonMissing.of(), + @JsonProperty("caller_lineno") + @ExcludeMissing + callerLineno: JsonValue = JsonMissing.of(), + @JsonProperty("completion_tokens") + @ExcludeMissing + completionTokens: JsonField = JsonMissing.of(), + @JsonProperty("end") @ExcludeMissing end: JsonField = JsonMissing.of(), + @JsonProperty("prompt_tokens") + @ExcludeMissing + promptTokens: JsonField = JsonMissing.of(), + @JsonProperty("start") @ExcludeMissing start: JsonField = JsonMissing.of(), + @JsonProperty("tokens") @ExcludeMissing tokens: JsonField = JsonMissing.of(), + ) : this( + callerFilename, + callerFunctionname, + callerLineno, + completionTokens, + end, + promptTokens, + start, + tokens, + mutableMapOf(), + ) + /** This metric is deprecated */ @JsonProperty("caller_filename") @ExcludeMissing @@ -1390,8 +1546,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * A unix timestamp recording when the section of code which produced the project logs event @@ -1400,7 +1555,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun end(): Optional = Optional.ofNullable(end.getNullable("end")) + fun end(): Optional = end.getOptional("end") /** * The number of tokens in the prompt used to generate the project logs event (only set if @@ -1409,8 +1564,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * A unix timestamp recording when the section of code which produced the project logs event @@ -1419,7 +1573,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun start(): Optional = Optional.ofNullable(start.getNullable("start")) + fun start(): Optional = start.getOptional("start") /** * The total number of tokens in the input and output of the project logs event. @@ -1427,7 +1581,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun tokens(): Optional = Optional.ofNullable(tokens.getNullable("tokens")) + fun tokens(): Optional = tokens.getOptional("tokens") /** * Returns the raw JSON value of [completionTokens]. @@ -1470,24 +1624,15 @@ private constructor( */ @JsonProperty("tokens") @ExcludeMissing fun _tokens(): JsonField = tokens + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metrics = apply { - if (validated) { - return@apply - } - - completionTokens() - end() - promptTokens() - start() - tokens() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1701,10 +1846,47 @@ private constructor( promptTokens, start, tokens, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Metrics = apply { + if (validated) { + return@apply + } + + completionTokens() + end() + promptTokens() + start() + tokens() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (completionTokens.asKnown().isPresent) 1 else 0) + + (if (end.asKnown().isPresent) 1 else 0) + + (if (promptTokens.asKnown().isPresent) 1 else 0) + + (if (start.asKnown().isPresent) 1 else 0) + + (if (tokens.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1732,28 +1914,17 @@ private constructor( * whether the summarization was covering similar concepts or not. You can use these scores to * help you sort, filter, and compare logs. */ - @NoAutoDetect class Scores @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Scores = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -1799,6 +1970,34 @@ private constructor( fun build(): Scores = Scores(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Scores = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectRetrieveParams.kt index 36e479aa..5fddd2dc 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [ProjectRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var projectId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScore.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScore.kt index 023cbd6f..48b771b0 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScore.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScore.kt @@ -8,10 +8,9 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect +import com.braintrustdata.api.core.allMaxBy import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -26,44 +25,63 @@ 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 /** A project score is a user-configured score, which can be manually-labeled through the UI */ -@NoAutoDetect class ProjectScore -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("score_type") - @ExcludeMissing - private val scoreType: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonProperty("categories") - @ExcludeMissing - private val categories: JsonField = JsonMissing.of(), - @JsonProperty("config") - @ExcludeMissing - private val config: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("position") - @ExcludeMissing - private val position: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val name: JsonField, + private val projectId: JsonField, + private val scoreType: JsonField, + private val userId: JsonField, + private val categories: JsonField, + private val config: JsonField, + private val created: JsonField, + private val description: JsonField, + private val position: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") @ExcludeMissing projectId: JsonField = JsonMissing.of(), + @JsonProperty("score_type") + @ExcludeMissing + scoreType: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + @JsonProperty("categories") + @ExcludeMissing + categories: JsonField = JsonMissing.of(), + @JsonProperty("config") + @ExcludeMissing + config: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("position") @ExcludeMissing position: JsonField = JsonMissing.of(), + ) : this( + id, + name, + projectId, + scoreType, + userId, + categories, + config, + created, + description, + position, + mutableMapOf(), + ) + /** * Unique identifier for the project score * @@ -108,14 +126,13 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun categories(): Optional = - Optional.ofNullable(categories.getNullable("categories")) + fun categories(): Optional = categories.getOptional("categories") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun config(): Optional = Optional.ofNullable(config.getNullable("config")) + fun config(): Optional = config.getOptional("config") /** * Date of project score creation @@ -123,7 +140,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Textual description of the project score @@ -131,8 +148,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun description(): Optional = description.getOptional("description") /** * An optional LexoRank-based string that sets the sort position for the score in the UI @@ -140,7 +156,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun position(): Optional = Optional.ofNullable(position.getNullable("position")) + fun position(): Optional = position.getOptional("position") /** * Returns the raw JSON value of [id]. @@ -216,29 +232,15 @@ private constructor( */ @JsonProperty("position") @ExcludeMissing fun _position(): JsonField = position + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ProjectScore = apply { - if (validated) { - return@apply - } - - id() - name() - projectId() - scoreType() - userId() - categories().ifPresent { it.validate() } - config().ifPresent { it.validate() } - created() - description() - position() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -475,10 +477,56 @@ private constructor( created, description, position, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): ProjectScore = apply { + if (validated) { + return@apply + } + + id() + name() + projectId() + scoreType().validate() + userId() + categories().ifPresent { it.validate() } + config().ifPresent { it.validate() } + created() + description() + position() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (scoreType.asKnown().getOrNull()?.validity() ?: 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + (categories.asKnown().getOrNull()?.validity() ?: 0) + + (config.asKnown().getOrNull()?.validity() ?: 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (position.asKnown().isPresent) 1 else 0) + /** For categorical-type project scores, the list of all categories */ @JsonDeserialize(using = Categories.Deserializer::class) @JsonSerialize(using = Categories.Serializer::class) @@ -516,14 +564,13 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { categorical != null -> visitor.visitCategorical(categorical) weighted != null -> visitor.visitWeighted(weighted) minimum != null -> visitor.visitMinimum(minimum) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -548,6 +595,35 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitCategorical(categorical: List) = + categorical.sumOf { it.validity().toInt() } + + override fun visitWeighted(weighted: Weighted) = weighted.validity() + + override fun visitMinimum(minimum: List) = minimum.size + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -615,21 +691,30 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Categories { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef>()) { - it.forEach { it.validate() } - } - ?.let { - return Categories(categorical = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Categories(weighted = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Categories(minimum = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Categories(weighted = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef>()) + ?.let { Categories(categorical = it, _json = json) }, + tryDeserialize(node, jacksonTypeRef>())?.let { + Categories(minimum = 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 -> Categories(_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 Categories(_json = json) } } @@ -651,28 +736,17 @@ private constructor( } /** For weighted-type project scores, the weights of each score */ - @NoAutoDetect class Weighted @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Weighted = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -721,6 +795,34 @@ private constructor( fun build(): Weighted = Weighted(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Weighted = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreCategory.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreCategory.kt index b4504114..92dcb461 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreCategory.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreCategory.kt @@ -6,27 +6,29 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 /** For categorical-type project scores, defines a single category */ -@NoAutoDetect class ProjectScoreCategory -@JsonCreator private constructor( - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("value") @ExcludeMissing private val value: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val value: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonField = JsonMissing.of(), + ) : this(name, value, mutableMapOf()) + /** * Name of the category * @@ -57,21 +59,15 @@ private constructor( */ @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ProjectScoreCategory = apply { - if (validated) { - return@apply - } - - name() - value() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -161,10 +157,39 @@ private constructor( ProjectScoreCategory( checkRequired("name", name), checkRequired("value", value), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): ProjectScoreCategory = apply { + if (validated) { + return@apply + } + + name() + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + (if (value.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreConfig.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreConfig.kt index 4ec3a301..6e3e4571 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreConfig.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreConfig.kt @@ -6,53 +6,54 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 -@NoAutoDetect class ProjectScoreConfig -@JsonCreator private constructor( - @JsonProperty("destination") - @ExcludeMissing - private val destination: JsonField = JsonMissing.of(), - @JsonProperty("multi_select") - @ExcludeMissing - private val multiSelect: JsonField = JsonMissing.of(), - @JsonProperty("online") - @ExcludeMissing - private val online: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val destination: JsonField, + private val multiSelect: JsonField, + private val online: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("destination") + @ExcludeMissing + destination: JsonField = JsonMissing.of(), + @JsonProperty("multi_select") + @ExcludeMissing + multiSelect: JsonField = JsonMissing.of(), + @JsonProperty("online") + @ExcludeMissing + online: JsonField = JsonMissing.of(), + ) : this(destination, multiSelect, online, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun destination(): Optional = - Optional.ofNullable(destination.getNullable("destination")) + fun destination(): Optional = destination.getOptional("destination") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun multiSelect(): Optional = - Optional.ofNullable(multiSelect.getNullable("multi_select")) + fun multiSelect(): Optional = multiSelect.getOptional("multi_select") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun online(): Optional = Optional.ofNullable(online.getNullable("online")) + fun online(): Optional = online.getOptional("online") /** * Returns the raw JSON value of [destination]. @@ -77,22 +78,15 @@ private constructor( */ @JsonProperty("online") @ExcludeMissing fun _online(): JsonField = online + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ProjectScoreConfig = apply { - if (validated) { - return@apply - } - - destination() - multiSelect() - online().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -192,9 +186,46 @@ private constructor( * Further updates to this [Builder] will not mutate the returned instance. */ fun build(): ProjectScoreConfig = - ProjectScoreConfig(destination, multiSelect, online, additionalProperties.toImmutable()) + ProjectScoreConfig( + destination, + multiSelect, + online, + additionalProperties.toMutableMap(), + ) } + private var validated: Boolean = false + + fun validate(): ProjectScoreConfig = apply { + if (validated) { + return@apply + } + + destination() + multiSelect() + online().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (destination.asKnown().isPresent) 1 else 0) + + (if (multiSelect.asKnown().isPresent) 1 else 0) + + (online.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreCreateParams.kt index 6b60c606..ca9cd18b 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreCreateParams.kt @@ -8,13 +8,12 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.allMaxBy import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -28,6 +27,7 @@ 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.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -137,364 +137,262 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun toBuilder() = Builder().from(this) - /** A project score is a user-configured score, which can be manually-labeled through the UI */ - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("score_type") - @ExcludeMissing - private val scoreType: JsonField = JsonMissing.of(), - @JsonProperty("categories") - @ExcludeMissing - private val categories: JsonField = JsonMissing.of(), - @JsonProperty("config") - @ExcludeMissing - private val config: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + companion object { /** - * Name of the project score + * Returns a mutable builder for constructing an instance of [ProjectScoreCreateParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .name() + * .projectId() + * .scoreType() + * ``` */ - fun name(): String = name.getRequired("name") + @JvmStatic fun builder() = Builder() + } - /** - * Unique identifier for the project that the project score belongs under - * - * @throws BraintrustInvalidDataException 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 projectId(): String = projectId.getRequired("project_id") + /** A builder for [ProjectScoreCreateParams]. */ + class Builder internal constructor() { - /** - * The type of the configured score - * - * @throws BraintrustInvalidDataException 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 scoreType(): ProjectScoreType = scoreType.getRequired("score_type") + 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(projectScoreCreateParams: ProjectScoreCreateParams) = apply { + body = projectScoreCreateParams.body.toBuilder() + additionalHeaders = projectScoreCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = projectScoreCreateParams.additionalQueryParams.toBuilder() + } /** - * For categorical-type project scores, the list of all categories + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [name] + * - [projectId] + * - [scoreType] + * - [categories] + * - [config] + * - etc. */ - fun categories(): Optional = - Optional.ofNullable(categories.getNullable("categories")) + fun body(body: Body) = apply { this.body = body.toBuilder() } - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun config(): Optional = - Optional.ofNullable(config.getNullable("config")) + /** Name of the project score */ + fun name(name: String) = apply { body.name(name) } /** - * Textual description of the project score + * Sets [Builder.name] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected 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 description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun name(name: JsonField) = apply { body.name(name) } - /** - * 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 + /** Unique identifier for the project that the project score belongs under */ + fun projectId(projectId: String) = apply { body.projectId(projectId) } /** - * Returns the raw JSON value of [projectId]. + * Sets [Builder.projectId] to an arbitrary JSON value. * - * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId + fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } - /** - * Returns the raw JSON value of [scoreType]. - * - * Unlike [scoreType], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("score_type") - @ExcludeMissing - fun _scoreType(): JsonField = scoreType + /** The type of the configured score */ + fun scoreType(scoreType: ProjectScoreType) = apply { body.scoreType(scoreType) } /** - * Returns the raw JSON value of [categories]. + * Sets [Builder.scoreType] to an arbitrary JSON value. * - * Unlike [categories], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.scoreType] with a well-typed [ProjectScoreType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("categories") - @ExcludeMissing - fun _categories(): JsonField = categories + fun scoreType(scoreType: JsonField) = apply { body.scoreType(scoreType) } - /** - * 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 + /** For categorical-type project scores, the list of all categories */ + fun categories(categories: Categories?) = apply { body.categories(categories) } + + /** Alias for calling [Builder.categories] with `categories.orElse(null)`. */ + fun categories(categories: Optional) = categories(categories.getOrNull()) /** - * Returns the raw JSON value of [description]. + * Sets [Builder.categories] to an arbitrary JSON value. * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.categories] with a well-typed [Categories] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } + fun categories(categories: JsonField) = apply { body.categories(categories) } - name() - projectId() - scoreType() - categories().ifPresent { it.validate() } - config().ifPresent { it.validate() } - description() - validated = true + /** Alias for calling [categories] with `Categories.ofCategorical(categorical)`. */ + fun categoriesOfCategorical(categorical: List) = apply { + body.categoriesOfCategorical(categorical) } - fun toBuilder() = Builder().from(this) - - companion object { + /** Alias for calling [categories] with `Categories.ofWeighted(weighted)`. */ + fun categories(weighted: Categories.Weighted) = apply { body.categories(weighted) } - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .scoreType() - * ``` - */ - @JvmStatic fun builder() = Builder() - } + /** Alias for calling [categories] with `Categories.ofMinimum(minimum)`. */ + fun categoriesOfMinimum(minimum: List) = apply { body.categoriesOfMinimum(minimum) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun config(config: ProjectScoreConfig?) = apply { body.config(config) } - private var name: JsonField? = null - private var projectId: JsonField? = null - private var scoreType: JsonField? = null - private var categories: JsonField = JsonMissing.of() - private var config: JsonField = JsonMissing.of() - private var description: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - projectId = body.projectId - scoreType = body.scoreType - categories = body.categories - config = body.config - description = body.description - additionalProperties = body.additionalProperties.toMutableMap() - } + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [ProjectScoreConfig] 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) } - /** Name of the project score */ - fun name(name: String) = name(JsonField.of(name)) + /** Textual description of the project score */ + fun description(description: String?) = apply { body.description(description) } - /** - * 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 } + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) - /** Unique identifier for the project that the project score belongs under */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { body.description(description) } - /** - * Sets [Builder.projectId] to an arbitrary JSON value. - * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - /** The type of the configured score */ - fun scoreType(scoreType: ProjectScoreType) = scoreType(JsonField.of(scoreType)) + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - /** - * Sets [Builder.scoreType] to an arbitrary JSON value. - * - * You should usually call [Builder.scoreType] with a well-typed [ProjectScoreType] - * value instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun scoreType(scoreType: JsonField) = apply { - this.scoreType = scoreType + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - /** For categorical-type project scores, the list of all categories */ - fun categories(categories: Categories?) = categories(JsonField.ofNullable(categories)) + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - /** Alias for calling [Builder.categories] with `categories.orElse(null)`. */ - fun categories(categories: Optional) = categories(categories.getOrNull()) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** - * Sets [Builder.categories] to an arbitrary JSON value. - * - * You should usually call [Builder.categories] with a well-typed [Categories] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun categories(categories: JsonField) = apply { - this.categories = categories - } + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Alias for calling [categories] with `Categories.ofCategorical(categorical)`. */ - fun categoriesOfCategorical(categorical: List) = - categories(Categories.ofCategorical(categorical)) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Alias for calling [categories] with `Categories.ofWeighted(weighted)`. */ - fun categories(weighted: Categories.Weighted) = - categories(Categories.ofWeighted(weighted)) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** Alias for calling [categories] with `Categories.ofMinimum(minimum)`. */ - fun categoriesOfMinimum(minimum: List) = - categories(Categories.ofMinimum(minimum)) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - fun config(config: ProjectScoreConfig?) = config(JsonField.ofNullable(config)) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.config] with `config.orElse(null)`. */ - fun config(config: Optional) = config(config.getOrNull()) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** - * Sets [Builder.config] to an arbitrary JSON value. - * - * You should usually call [Builder.config] with a well-typed [ProjectScoreConfig] 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 replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** Textual description of the project score */ - fun description(description: String?) = description(JsonField.ofNullable(description)) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .scoreType() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("name", name), - checkRequired("projectId", projectId), - checkRequired("scoreType", scoreType), - categories, - config, - description, - additionalProperties.toImmutable(), - ) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && scoreType == other.scoreType && categories == other.categories && config == other.config && description == other.description && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, projectId, scoreType, categories, config, description, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{name=$name, projectId=$projectId, scoreType=$scoreType, categories=$categories, config=$config, description=$description, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [ProjectScoreCreateParams]. + * Returns an immutable instance of [ProjectScoreCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java @@ -502,252 +400,398 @@ private constructor( * .projectId() * .scoreType() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): ProjectScoreCreateParams = + ProjectScoreCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [ProjectScoreCreateParams]. */ - @NoAutoDetect - class Builder internal constructor() { + fun _body(): Body = body - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + override fun _headers(): Headers = additionalHeaders - @JvmSynthetic - internal fun from(projectScoreCreateParams: ProjectScoreCreateParams) = apply { - body = projectScoreCreateParams.body.toBuilder() - additionalHeaders = projectScoreCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = projectScoreCreateParams.additionalQueryParams.toBuilder() - } + override fun _queryParams(): QueryParams = additionalQueryParams - /** Name of the project score */ - fun name(name: String) = apply { body.name(name) } + /** A project score is a user-configured score, which can be manually-labeled through the UI */ + class Body + private constructor( + private val name: JsonField, + private val projectId: JsonField, + private val scoreType: JsonField, + private val categories: JsonField, + private val config: JsonField, + private val description: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") + @ExcludeMissing + projectId: JsonField = JsonMissing.of(), + @JsonProperty("score_type") + @ExcludeMissing + scoreType: JsonField = JsonMissing.of(), + @JsonProperty("categories") + @ExcludeMissing + categories: JsonField = JsonMissing.of(), + @JsonProperty("config") + @ExcludeMissing + config: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + ) : this(name, projectId, scoreType, categories, config, description, mutableMapOf()) /** - * Sets [Builder.name] to an arbitrary JSON value. + * Name of the project score * - * 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. + * @throws BraintrustInvalidDataException 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(name: JsonField) = apply { body.name(name) } - - /** Unique identifier for the project that the project score belongs under */ - fun projectId(projectId: String) = apply { body.projectId(projectId) } + fun name(): String = name.getRequired("name") /** - * Sets [Builder.projectId] to an arbitrary JSON value. + * Unique identifier for the project that the project score belongs under * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException 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 projectId(projectId: JsonField) = apply { body.projectId(projectId) } - - /** The type of the configured score */ - fun scoreType(scoreType: ProjectScoreType) = apply { body.scoreType(scoreType) } + fun projectId(): String = projectId.getRequired("project_id") /** - * Sets [Builder.scoreType] to an arbitrary JSON value. + * The type of the configured score * - * You should usually call [Builder.scoreType] with a well-typed [ProjectScoreType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException 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 scoreType(scoreType: JsonField) = apply { body.scoreType(scoreType) } - - /** For categorical-type project scores, the list of all categories */ - fun categories(categories: Categories?) = apply { body.categories(categories) } - - /** Alias for calling [Builder.categories] with `categories.orElse(null)`. */ - fun categories(categories: Optional) = categories(categories.getOrNull()) + fun scoreType(): ProjectScoreType = scoreType.getRequired("score_type") /** - * Sets [Builder.categories] to an arbitrary JSON value. + * For categorical-type project scores, the list of all categories * - * You should usually call [Builder.categories] with a well-typed [Categories] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun categories(categories: JsonField) = apply { body.categories(categories) } - - /** Alias for calling [categories] with `Categories.ofCategorical(categorical)`. */ - fun categoriesOfCategorical(categorical: List) = apply { - body.categoriesOfCategorical(categorical) - } + fun categories(): Optional = categories.getOptional("categories") - /** Alias for calling [categories] with `Categories.ofWeighted(weighted)`. */ - fun categories(weighted: Categories.Weighted) = apply { body.categories(weighted) } + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun config(): Optional = config.getOptional("config") - /** Alias for calling [categories] with `Categories.ofMinimum(minimum)`. */ - fun categoriesOfMinimum(minimum: List) = apply { body.categoriesOfMinimum(minimum) } + /** + * Textual description of the project score + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") - fun config(config: ProjectScoreConfig?) = apply { body.config(config) } + /** + * 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 - /** Alias for calling [Builder.config] with `config.orElse(null)`. */ - fun config(config: Optional) = config(config.getOrNull()) + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId /** - * Sets [Builder.config] to an arbitrary JSON value. + * Returns the raw JSON value of [scoreType]. * - * You should usually call [Builder.config] with a well-typed [ProjectScoreConfig] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * Unlike [scoreType], this method doesn't throw if the JSON field has an unexpected type. */ - fun config(config: JsonField) = apply { body.config(config) } + @JsonProperty("score_type") + @ExcludeMissing + fun _scoreType(): JsonField = scoreType - /** Textual description of the project score */ - fun description(description: String?) = apply { body.description(description) } + /** + * Returns the raw JSON value of [categories]. + * + * Unlike [categories], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("categories") + @ExcludeMissing + fun _categories(): JsonField = categories - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + /** + * 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 /** - * Sets [Builder.description] to an arbitrary JSON value. + * Returns the raw JSON value of [description]. * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. */ - fun description(description: JsonField) = apply { body.description(description) } + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(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 + * .name() + * .projectId() + * .scoreType() + * ``` + */ + @JvmStatic fun builder() = Builder() } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var projectId: JsonField? = null + private var scoreType: JsonField? = null + private var categories: JsonField = JsonMissing.of() + private var config: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + projectId = body.projectId + scoreType = body.scoreType + categories = body.categories + config = body.config + description = body.description + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the project score */ + 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 } + + /** Unique identifier for the project that the project score belongs under */ + fun projectId(projectId: String) = projectId(JsonField.of(projectId)) + + /** + * Sets [Builder.projectId] to an arbitrary JSON value. + * + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun projectId(projectId: JsonField) = apply { this.projectId = projectId } + + /** The type of the configured score */ + fun scoreType(scoreType: ProjectScoreType) = scoreType(JsonField.of(scoreType)) + + /** + * Sets [Builder.scoreType] to an arbitrary JSON value. + * + * You should usually call [Builder.scoreType] with a well-typed [ProjectScoreType] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun scoreType(scoreType: JsonField) = apply { + this.scoreType = scoreType } - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** For categorical-type project scores, the list of all categories */ + fun categories(categories: Categories?) = categories(JsonField.ofNullable(categories)) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** Alias for calling [Builder.categories] with `categories.orElse(null)`. */ + fun categories(categories: Optional) = categories(categories.getOrNull()) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Sets [Builder.categories] to an arbitrary JSON value. + * + * You should usually call [Builder.categories] with a well-typed [Categories] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun categories(categories: JsonField) = apply { + this.categories = categories + } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** Alias for calling [categories] with `Categories.ofCategorical(categorical)`. */ + fun categoriesOfCategorical(categorical: List) = + categories(Categories.ofCategorical(categorical)) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** Alias for calling [categories] with `Categories.ofWeighted(weighted)`. */ + fun categories(weighted: Categories.Weighted) = + categories(Categories.ofWeighted(weighted)) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** Alias for calling [categories] with `Categories.ofMinimum(minimum)`. */ + fun categoriesOfMinimum(minimum: List) = + categories(Categories.ofMinimum(minimum)) - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + fun config(config: ProjectScoreConfig?) = config(JsonField.ofNullable(config)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [ProjectScoreConfig] 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 replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** Textual description of the project score */ + fun description(description: String?) = description(JsonField.ofNullable(description)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * .scoreType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("name", name), + checkRequired("projectId", projectId), + checkRequired("scoreType", scoreType), + categories, + config, + description, + additionalProperties.toMutableMap(), + ) } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + private var validated: Boolean = false - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun validate(): Body = apply { + if (validated) { + return@apply } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) + name() + projectId() + scoreType().validate() + categories().ifPresent { it.validate() } + config().ifPresent { it.validate() } + description() + validated = true } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (scoreType.asKnown().getOrNull()?.validity() ?: 0) + + (categories.asKnown().getOrNull()?.validity() ?: 0) + + (config.asKnown().getOrNull()?.validity() ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && scoreType == other.scoreType && categories == other.categories && config == other.config && description == other.description && additionalProperties == other.additionalProperties /* spotless:on */ } - /** - * Returns an immutable instance of [ProjectScoreCreateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .scoreType() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): ProjectScoreCreateParams = - ProjectScoreCreateParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, projectId, scoreType, categories, config, description, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, projectId=$projectId, scoreType=$scoreType, categories=$categories, config=$config, description=$description, additionalProperties=$additionalProperties}" } /** For categorical-type project scores, the list of all categories */ @@ -787,14 +831,13 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { categorical != null -> visitor.visitCategorical(categorical) weighted != null -> visitor.visitWeighted(weighted) minimum != null -> visitor.visitMinimum(minimum) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -819,6 +862,35 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitCategorical(categorical: List) = + categorical.sumOf { it.validity().toInt() } + + override fun visitWeighted(weighted: Weighted) = weighted.validity() + + override fun visitMinimum(minimum: List) = minimum.size + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -886,21 +958,30 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Categories { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef>()) { - it.forEach { it.validate() } - } - ?.let { - return Categories(categorical = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Categories(weighted = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Categories(minimum = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Categories(weighted = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef>()) + ?.let { Categories(categorical = it, _json = json) }, + tryDeserialize(node, jacksonTypeRef>())?.let { + Categories(minimum = 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 -> Categories(_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 Categories(_json = json) } } @@ -922,28 +1003,17 @@ private constructor( } /** For weighted-type project scores, the weights of each score */ - @NoAutoDetect class Weighted @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Weighted = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -992,6 +1062,34 @@ private constructor( fun build(): Weighted = Weighted(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Weighted = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreDeleteParams.kt index 8e26501a..e9f282f5 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreDeleteParams.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,26 +23,11 @@ private constructor( /** ProjectScore id */ fun projectScoreId(): String = projectScoreId - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectScoreId - else -> "" - } - } + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -61,7 +45,6 @@ private constructor( } /** A builder for [ProjectScoreDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var projectScoreId: String? = null @@ -222,6 +205,19 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectScoreId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListPage.kt index 904e8477..ad6b1c2d 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListPage.kt @@ -2,171 +2,115 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.ProjectScoreService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all project_scores. The project_scores are sorted by creation date, with the most - * recently-created project_scores coming first - */ +/** @see [ProjectScoreService.list] */ class ProjectScoreListPage private constructor( - private val projectScoresService: ProjectScoreService, + private val service: ProjectScoreService, private val params: ProjectScoreListParams, - private val response: Response, + private val response: ProjectScoreListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [ProjectScoreListPageResponse], but gracefully handles missing data. + * + * @see [ProjectScoreListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ProjectScoreListPage && projectScoresService == other.projectScoresService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(projectScoresService, params, response) /* spotless:on */ - - override fun toString() = - "ProjectScoreListPage{projectScoresService=$projectScoresService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - ProjectScoreListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - ProjectScoreListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { projectScoresService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of( - projectScoresService: ProjectScoreService, - params: ProjectScoreListParams, - response: Response, - ) = ProjectScoreListPage(projectScoresService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") - private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): ProjectScoreListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): ProjectScoreListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [ProjectScoreListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [ProjectScoreListPage]. */ + class Builder internal constructor() { - companion object { + private var service: ProjectScoreService? = null + private var params: ProjectScoreListParams? = null + private var response: ProjectScoreListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [ProjectScoreListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(projectScoreListPage: ProjectScoreListPage) = apply { + service = projectScoreListPage.service + params = projectScoreListPage.params + response = projectScoreListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: ProjectScoreService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: ProjectScoreListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ProjectScoreListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ProjectScoreListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectScoreListPage = + ProjectScoreListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: ProjectScoreListPage) : Iterable { @@ -187,4 +131,17 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ProjectScoreListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "ProjectScoreListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListPageAsync.kt index 0f5c5540..66769492 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListPageAsync.kt @@ -2,176 +2,119 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.ProjectScoreServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all project_scores. The project_scores are sorted by creation date, with the most - * recently-created project_scores coming first - */ +/** @see [ProjectScoreServiceAsync.list] */ class ProjectScoreListPageAsync private constructor( - private val projectScoresService: ProjectScoreServiceAsync, + private val service: ProjectScoreServiceAsync, private val params: ProjectScoreListParams, - private val response: Response, + private val response: ProjectScoreListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [ProjectScoreListPageResponse], but gracefully handles missing data. + * + * @see [ProjectScoreListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ProjectScoreListPageAsync && projectScoresService == other.projectScoresService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(projectScoresService, params, response) /* spotless:on */ - - override fun toString() = - "ProjectScoreListPageAsync{projectScoresService=$projectScoresService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - ProjectScoreListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - ProjectScoreListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { projectScoresService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of( - projectScoresService: ProjectScoreServiceAsync, - params: ProjectScoreListParams, - response: Response, - ) = ProjectScoreListPageAsync(projectScoresService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") - private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): ProjectScoreListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): ProjectScoreListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [ProjectScoreListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [ProjectScoreListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: ProjectScoreServiceAsync? = null + private var params: ProjectScoreListParams? = null + private var response: ProjectScoreListPageResponse? = null - /** - * Returns a mutable builder for constructing an instance of - * [ProjectScoreListPageAsync]. - */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(projectScoreListPageAsync: ProjectScoreListPageAsync) = apply { + service = projectScoreListPageAsync.service + params = projectScoreListPageAsync.params + response = projectScoreListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: ProjectScoreServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: ProjectScoreListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ProjectScoreListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ProjectScoreListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectScoreListPageAsync = + ProjectScoreListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: ProjectScoreListPageAsync) { @@ -199,4 +142,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ProjectScoreListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "ProjectScoreListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListPageResponse.kt new file mode 100644 index 00000000..de075aa9 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListPageResponse.kt @@ -0,0 +1,194 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class ProjectScoreListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") + @ExcludeMissing + objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of project_score objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [ProjectScoreListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectScoreListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(projectScoreListPageResponse: ProjectScoreListPageResponse) = apply { + objects = projectScoreListPageResponse.objects.map { it.toMutableList() } + additionalProperties = projectScoreListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of project_score objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [ProjectScore] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: ProjectScore) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ProjectScoreListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectScoreListPageResponse = + ProjectScoreListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ProjectScoreListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ProjectScoreListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProjectScoreListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListParams.kt index a1946a16..0b850233 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListParams.kt @@ -2,22 +2,10 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -87,46 +75,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - endingBefore?.let { put("ending_before", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - orgName?.let { put("org_name", it) } - projectId?.let { put("project_id", it) } - projectName?.let { put("project_name", it) } - projectScoreName?.let { put("project_score_name", it) } - scoreType?.accept( - object : ScoreType.Visitor { - override fun visitProject(project: ProjectScoreType) { - put("score_type", project.asString()) - } - - override fun visitProjectScoreTypes( - projectScoreTypes: List - ) { - put("score_type", projectScoreTypes.joinToString(",") { it.asString() }) - } - } - ) - startingAfter?.let { put("starting_after", it) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -138,7 +86,6 @@ private constructor( } /** A builder for [ProjectScoreListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var endingBefore: String? = null @@ -382,17 +329,54 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + endingBefore?.let { put("ending_before", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + orgName?.let { put("org_name", it) } + projectId?.let { put("project_id", it) } + projectName?.let { put("project_name", it) } + projectScoreName?.let { put("project_score_name", it) } + scoreType?.accept( + object : ScoreType.Visitor { + override fun visitProject(project: ProjectScoreType) { + put("score_type", project.toString()) + } + + override fun visitProjectScoreTypes( + projectScoreTypes: List + ) { + put("score_type", projectScoreTypes.joinToString(",") { it.toString() }) + } + } + ) + startingAfter?.let { put("starting_after", it) } + putAll(additionalQueryParams) + } + .build() + /** * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -407,15 +391,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -431,7 +412,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -448,62 +428,14 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } /** The type of the configured score */ - @JsonDeserialize(using = ScoreType.Deserializer::class) - @JsonSerialize(using = ScoreType.Serializer::class) class ScoreType private constructor( private val project: ProjectScoreType? = null, private val projectScoreTypes: List? = null, - private val _json: JsonValue? = null, ) { /** The type of the configured score */ @@ -524,15 +456,12 @@ private constructor( fun asProjectScoreTypes(): List = projectScoreTypes.getOrThrow("projectScoreTypes") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { project != null -> visitor.visitProject(project) projectScoreTypes != null -> visitor.visitProjectScoreTypes(projectScoreTypes) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid ScoreType") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -548,7 +477,6 @@ private constructor( when { project != null -> "ScoreType{project=$project}" projectScoreTypes != null -> "ScoreType{projectScoreTypes=$projectScoreTypes}" - _json != null -> "ScoreType{_unknown=$_json}" else -> throw IllegalStateException("Invalid ScoreType") } @@ -573,53 +501,6 @@ private constructor( /** The type of the configured score */ fun visitProjectScoreTypes(projectScoreTypes: List): T - - /** - * Maps an unknown variant of [ScoreType] to a value of type [T]. - * - * An instance of [ScoreType] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown ScoreType: $json") - } - } - - internal class Deserializer : BaseDeserializer(ScoreType::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): ScoreType { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return ScoreType(project = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return ScoreType(projectScoreTypes = it, _json = json) - } - - return ScoreType(_json = json) - } - } - - internal class Serializer : BaseSerializer(ScoreType::class) { - - override fun serialize( - value: ScoreType, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.project != null -> generator.writeObject(value.project) - value.projectScoreTypes != null -> - generator.writeObject(value.projectScoreTypes) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid ScoreType") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreReplaceParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreReplaceParams.kt index 439137c0..4f9186a0 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreReplaceParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreReplaceParams.kt @@ -8,13 +8,12 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.allMaxBy import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -28,6 +27,7 @@ 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.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -138,364 +138,262 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun toBuilder() = Builder().from(this) - /** A project score is a user-configured score, which can be manually-labeled through the UI */ - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("score_type") - @ExcludeMissing - private val scoreType: JsonField = JsonMissing.of(), - @JsonProperty("categories") - @ExcludeMissing - private val categories: JsonField = JsonMissing.of(), - @JsonProperty("config") - @ExcludeMissing - private val config: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + companion object { /** - * Name of the project score + * Returns a mutable builder for constructing an instance of [ProjectScoreReplaceParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .name() + * .projectId() + * .scoreType() + * ``` */ - fun name(): String = name.getRequired("name") + @JvmStatic fun builder() = Builder() + } - /** - * Unique identifier for the project that the project score belongs under - * - * @throws BraintrustInvalidDataException 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 projectId(): String = projectId.getRequired("project_id") + /** A builder for [ProjectScoreReplaceParams]. */ + class Builder internal constructor() { - /** - * The type of the configured score - * - * @throws BraintrustInvalidDataException 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 scoreType(): ProjectScoreType = scoreType.getRequired("score_type") + 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(projectScoreReplaceParams: ProjectScoreReplaceParams) = apply { + body = projectScoreReplaceParams.body.toBuilder() + additionalHeaders = projectScoreReplaceParams.additionalHeaders.toBuilder() + additionalQueryParams = projectScoreReplaceParams.additionalQueryParams.toBuilder() + } /** - * For categorical-type project scores, the list of all categories + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [name] + * - [projectId] + * - [scoreType] + * - [categories] + * - [config] + * - etc. */ - fun categories(): Optional = - Optional.ofNullable(categories.getNullable("categories")) + fun body(body: Body) = apply { this.body = body.toBuilder() } - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun config(): Optional = - Optional.ofNullable(config.getNullable("config")) + /** Name of the project score */ + fun name(name: String) = apply { body.name(name) } /** - * Textual description of the project score + * Sets [Builder.name] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected 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 description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun name(name: JsonField) = apply { body.name(name) } - /** - * 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 + /** Unique identifier for the project that the project score belongs under */ + fun projectId(projectId: String) = apply { body.projectId(projectId) } /** - * Returns the raw JSON value of [projectId]. + * Sets [Builder.projectId] to an arbitrary JSON value. * - * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId + fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } - /** - * Returns the raw JSON value of [scoreType]. - * - * Unlike [scoreType], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("score_type") - @ExcludeMissing - fun _scoreType(): JsonField = scoreType + /** The type of the configured score */ + fun scoreType(scoreType: ProjectScoreType) = apply { body.scoreType(scoreType) } /** - * Returns the raw JSON value of [categories]. + * Sets [Builder.scoreType] to an arbitrary JSON value. * - * Unlike [categories], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.scoreType] with a well-typed [ProjectScoreType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("categories") - @ExcludeMissing - fun _categories(): JsonField = categories + fun scoreType(scoreType: JsonField) = apply { body.scoreType(scoreType) } - /** - * 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 + /** For categorical-type project scores, the list of all categories */ + fun categories(categories: Categories?) = apply { body.categories(categories) } + + /** Alias for calling [Builder.categories] with `categories.orElse(null)`. */ + fun categories(categories: Optional) = categories(categories.getOrNull()) /** - * Returns the raw JSON value of [description]. + * Sets [Builder.categories] to an arbitrary JSON value. * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.categories] with a well-typed [Categories] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } + fun categories(categories: JsonField) = apply { body.categories(categories) } - name() - projectId() - scoreType() - categories().ifPresent { it.validate() } - config().ifPresent { it.validate() } - description() - validated = true + /** Alias for calling [categories] with `Categories.ofCategorical(categorical)`. */ + fun categoriesOfCategorical(categorical: List) = apply { + body.categoriesOfCategorical(categorical) } - fun toBuilder() = Builder().from(this) - - companion object { + /** Alias for calling [categories] with `Categories.ofWeighted(weighted)`. */ + fun categories(weighted: Categories.Weighted) = apply { body.categories(weighted) } - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .scoreType() - * ``` - */ - @JvmStatic fun builder() = Builder() - } + /** Alias for calling [categories] with `Categories.ofMinimum(minimum)`. */ + fun categoriesOfMinimum(minimum: List) = apply { body.categoriesOfMinimum(minimum) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun config(config: ProjectScoreConfig?) = apply { body.config(config) } - private var name: JsonField? = null - private var projectId: JsonField? = null - private var scoreType: JsonField? = null - private var categories: JsonField = JsonMissing.of() - private var config: JsonField = JsonMissing.of() - private var description: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - projectId = body.projectId - scoreType = body.scoreType - categories = body.categories - config = body.config - description = body.description - additionalProperties = body.additionalProperties.toMutableMap() - } + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [ProjectScoreConfig] 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) } - /** Name of the project score */ - fun name(name: String) = name(JsonField.of(name)) + /** Textual description of the project score */ + fun description(description: String?) = apply { body.description(description) } - /** - * 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 } + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) - /** Unique identifier for the project that the project score belongs under */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { body.description(description) } - /** - * Sets [Builder.projectId] to an arbitrary JSON value. - * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - /** The type of the configured score */ - fun scoreType(scoreType: ProjectScoreType) = scoreType(JsonField.of(scoreType)) + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - /** - * Sets [Builder.scoreType] to an arbitrary JSON value. - * - * You should usually call [Builder.scoreType] with a well-typed [ProjectScoreType] - * value instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun scoreType(scoreType: JsonField) = apply { - this.scoreType = scoreType + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - /** For categorical-type project scores, the list of all categories */ - fun categories(categories: Categories?) = categories(JsonField.ofNullable(categories)) + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - /** Alias for calling [Builder.categories] with `categories.orElse(null)`. */ - fun categories(categories: Optional) = categories(categories.getOrNull()) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** - * Sets [Builder.categories] to an arbitrary JSON value. - * - * You should usually call [Builder.categories] with a well-typed [Categories] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun categories(categories: JsonField) = apply { - this.categories = categories - } + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Alias for calling [categories] with `Categories.ofCategorical(categorical)`. */ - fun categoriesOfCategorical(categorical: List) = - categories(Categories.ofCategorical(categorical)) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Alias for calling [categories] with `Categories.ofWeighted(weighted)`. */ - fun categories(weighted: Categories.Weighted) = - categories(Categories.ofWeighted(weighted)) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** Alias for calling [categories] with `Categories.ofMinimum(minimum)`. */ - fun categoriesOfMinimum(minimum: List) = - categories(Categories.ofMinimum(minimum)) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - fun config(config: ProjectScoreConfig?) = config(JsonField.ofNullable(config)) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.config] with `config.orElse(null)`. */ - fun config(config: Optional) = config(config.getOrNull()) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** - * Sets [Builder.config] to an arbitrary JSON value. - * - * You should usually call [Builder.config] with a well-typed [ProjectScoreConfig] 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 replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** Textual description of the project score */ - fun description(description: String?) = description(JsonField.ofNullable(description)) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .scoreType() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("name", name), - checkRequired("projectId", projectId), - checkRequired("scoreType", scoreType), - categories, - config, - description, - additionalProperties.toImmutable(), - ) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && scoreType == other.scoreType && categories == other.categories && config == other.config && description == other.description && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, projectId, scoreType, categories, config, description, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{name=$name, projectId=$projectId, scoreType=$scoreType, categories=$categories, config=$config, description=$description, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [ProjectScoreReplaceParams]. + * Returns an immutable instance of [ProjectScoreReplaceParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java @@ -503,252 +401,398 @@ private constructor( * .projectId() * .scoreType() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): ProjectScoreReplaceParams = + ProjectScoreReplaceParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [ProjectScoreReplaceParams]. */ - @NoAutoDetect - class Builder internal constructor() { + fun _body(): Body = body - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + override fun _headers(): Headers = additionalHeaders - @JvmSynthetic - internal fun from(projectScoreReplaceParams: ProjectScoreReplaceParams) = apply { - body = projectScoreReplaceParams.body.toBuilder() - additionalHeaders = projectScoreReplaceParams.additionalHeaders.toBuilder() - additionalQueryParams = projectScoreReplaceParams.additionalQueryParams.toBuilder() - } + override fun _queryParams(): QueryParams = additionalQueryParams - /** Name of the project score */ - fun name(name: String) = apply { body.name(name) } + /** A project score is a user-configured score, which can be manually-labeled through the UI */ + class Body + private constructor( + private val name: JsonField, + private val projectId: JsonField, + private val scoreType: JsonField, + private val categories: JsonField, + private val config: JsonField, + private val description: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") + @ExcludeMissing + projectId: JsonField = JsonMissing.of(), + @JsonProperty("score_type") + @ExcludeMissing + scoreType: JsonField = JsonMissing.of(), + @JsonProperty("categories") + @ExcludeMissing + categories: JsonField = JsonMissing.of(), + @JsonProperty("config") + @ExcludeMissing + config: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + ) : this(name, projectId, scoreType, categories, config, description, mutableMapOf()) /** - * Sets [Builder.name] to an arbitrary JSON value. + * Name of the project score * - * 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. + * @throws BraintrustInvalidDataException 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(name: JsonField) = apply { body.name(name) } - - /** Unique identifier for the project that the project score belongs under */ - fun projectId(projectId: String) = apply { body.projectId(projectId) } + fun name(): String = name.getRequired("name") /** - * Sets [Builder.projectId] to an arbitrary JSON value. + * Unique identifier for the project that the project score belongs under * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException 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 projectId(projectId: JsonField) = apply { body.projectId(projectId) } - - /** The type of the configured score */ - fun scoreType(scoreType: ProjectScoreType) = apply { body.scoreType(scoreType) } + fun projectId(): String = projectId.getRequired("project_id") /** - * Sets [Builder.scoreType] to an arbitrary JSON value. + * The type of the configured score * - * You should usually call [Builder.scoreType] with a well-typed [ProjectScoreType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException 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 scoreType(scoreType: JsonField) = apply { body.scoreType(scoreType) } - - /** For categorical-type project scores, the list of all categories */ - fun categories(categories: Categories?) = apply { body.categories(categories) } - - /** Alias for calling [Builder.categories] with `categories.orElse(null)`. */ - fun categories(categories: Optional) = categories(categories.getOrNull()) + fun scoreType(): ProjectScoreType = scoreType.getRequired("score_type") /** - * Sets [Builder.categories] to an arbitrary JSON value. + * For categorical-type project scores, the list of all categories * - * You should usually call [Builder.categories] with a well-typed [Categories] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun categories(categories: JsonField) = apply { body.categories(categories) } - - /** Alias for calling [categories] with `Categories.ofCategorical(categorical)`. */ - fun categoriesOfCategorical(categorical: List) = apply { - body.categoriesOfCategorical(categorical) - } + fun categories(): Optional = categories.getOptional("categories") - /** Alias for calling [categories] with `Categories.ofWeighted(weighted)`. */ - fun categories(weighted: Categories.Weighted) = apply { body.categories(weighted) } + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun config(): Optional = config.getOptional("config") - /** Alias for calling [categories] with `Categories.ofMinimum(minimum)`. */ - fun categoriesOfMinimum(minimum: List) = apply { body.categoriesOfMinimum(minimum) } + /** + * Textual description of the project score + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") - fun config(config: ProjectScoreConfig?) = apply { body.config(config) } + /** + * 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 - /** Alias for calling [Builder.config] with `config.orElse(null)`. */ - fun config(config: Optional) = config(config.getOrNull()) + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId /** - * Sets [Builder.config] to an arbitrary JSON value. + * Returns the raw JSON value of [scoreType]. * - * You should usually call [Builder.config] with a well-typed [ProjectScoreConfig] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * Unlike [scoreType], this method doesn't throw if the JSON field has an unexpected type. */ - fun config(config: JsonField) = apply { body.config(config) } + @JsonProperty("score_type") + @ExcludeMissing + fun _scoreType(): JsonField = scoreType - /** Textual description of the project score */ - fun description(description: String?) = apply { body.description(description) } + /** + * Returns the raw JSON value of [categories]. + * + * Unlike [categories], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("categories") + @ExcludeMissing + fun _categories(): JsonField = categories - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + /** + * 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 /** - * Sets [Builder.description] to an arbitrary JSON value. + * Returns the raw JSON value of [description]. * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. */ - fun description(description: JsonField) = apply { body.description(description) } + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(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 + * .name() + * .projectId() + * .scoreType() + * ``` + */ + @JvmStatic fun builder() = Builder() } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var projectId: JsonField? = null + private var scoreType: JsonField? = null + private var categories: JsonField = JsonMissing.of() + private var config: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + projectId = body.projectId + scoreType = body.scoreType + categories = body.categories + config = body.config + description = body.description + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the project score */ + 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 } + + /** Unique identifier for the project that the project score belongs under */ + fun projectId(projectId: String) = projectId(JsonField.of(projectId)) + + /** + * Sets [Builder.projectId] to an arbitrary JSON value. + * + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun projectId(projectId: JsonField) = apply { this.projectId = projectId } + + /** The type of the configured score */ + fun scoreType(scoreType: ProjectScoreType) = scoreType(JsonField.of(scoreType)) + + /** + * Sets [Builder.scoreType] to an arbitrary JSON value. + * + * You should usually call [Builder.scoreType] with a well-typed [ProjectScoreType] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun scoreType(scoreType: JsonField) = apply { + this.scoreType = scoreType } - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** For categorical-type project scores, the list of all categories */ + fun categories(categories: Categories?) = categories(JsonField.ofNullable(categories)) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** Alias for calling [Builder.categories] with `categories.orElse(null)`. */ + fun categories(categories: Optional) = categories(categories.getOrNull()) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Sets [Builder.categories] to an arbitrary JSON value. + * + * You should usually call [Builder.categories] with a well-typed [Categories] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun categories(categories: JsonField) = apply { + this.categories = categories + } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** Alias for calling [categories] with `Categories.ofCategorical(categorical)`. */ + fun categoriesOfCategorical(categorical: List) = + categories(Categories.ofCategorical(categorical)) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** Alias for calling [categories] with `Categories.ofWeighted(weighted)`. */ + fun categories(weighted: Categories.Weighted) = + categories(Categories.ofWeighted(weighted)) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** Alias for calling [categories] with `Categories.ofMinimum(minimum)`. */ + fun categoriesOfMinimum(minimum: List) = + categories(Categories.ofMinimum(minimum)) - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + fun config(config: ProjectScoreConfig?) = config(JsonField.ofNullable(config)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [ProjectScoreConfig] 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 replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** Textual description of the project score */ + fun description(description: String?) = description(JsonField.ofNullable(description)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * .scoreType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("name", name), + checkRequired("projectId", projectId), + checkRequired("scoreType", scoreType), + categories, + config, + description, + additionalProperties.toMutableMap(), + ) } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + private var validated: Boolean = false - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun validate(): Body = apply { + if (validated) { + return@apply } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) + name() + projectId() + scoreType().validate() + categories().ifPresent { it.validate() } + config().ifPresent { it.validate() } + description() + validated = true } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (scoreType.asKnown().getOrNull()?.validity() ?: 0) + + (categories.asKnown().getOrNull()?.validity() ?: 0) + + (config.asKnown().getOrNull()?.validity() ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && scoreType == other.scoreType && categories == other.categories && config == other.config && description == other.description && additionalProperties == other.additionalProperties /* spotless:on */ } - /** - * Returns an immutable instance of [ProjectScoreReplaceParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .scoreType() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): ProjectScoreReplaceParams = - ProjectScoreReplaceParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, projectId, scoreType, categories, config, description, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, projectId=$projectId, scoreType=$scoreType, categories=$categories, config=$config, description=$description, additionalProperties=$additionalProperties}" } /** For categorical-type project scores, the list of all categories */ @@ -788,14 +832,13 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { categorical != null -> visitor.visitCategorical(categorical) weighted != null -> visitor.visitWeighted(weighted) minimum != null -> visitor.visitMinimum(minimum) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -820,6 +863,35 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitCategorical(categorical: List) = + categorical.sumOf { it.validity().toInt() } + + override fun visitWeighted(weighted: Weighted) = weighted.validity() + + override fun visitMinimum(minimum: List) = minimum.size + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -887,21 +959,30 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Categories { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef>()) { - it.forEach { it.validate() } - } - ?.let { - return Categories(categorical = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Categories(weighted = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Categories(minimum = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Categories(weighted = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef>()) + ?.let { Categories(categorical = it, _json = json) }, + tryDeserialize(node, jacksonTypeRef>())?.let { + Categories(minimum = 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 -> Categories(_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 Categories(_json = json) } } @@ -923,28 +1004,17 @@ private constructor( } /** For weighted-type project scores, the weights of each score */ - @NoAutoDetect class Weighted @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Weighted = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -993,6 +1063,34 @@ private constructor( fun build(): Weighted = Weighted(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Weighted = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreRetrieveParams.kt index e2694fa2..ee9e6b7c 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectScoreId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [ProjectScoreRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var projectScoreId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectScoreId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreType.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreType.kt index 59dff6a1..6951cec7 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreType.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreType.kt @@ -125,6 +125,32 @@ class ProjectScoreType @JsonCreator private constructor(private val value: JsonF fun asString(): String = _value().asString().orElseThrow { BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ProjectScoreType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreUpdateParams.kt index f008ac19..3e601691 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreUpdateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreUpdateParams.kt @@ -8,13 +8,12 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.allMaxBy import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -28,6 +27,7 @@ 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.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -127,575 +127,615 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) - override fun _headers(): Headers = additionalHeaders + companion object { - override fun _queryParams(): QueryParams = additionalQueryParams + /** + * Returns a mutable builder for constructing an instance of [ProjectScoreUpdateParams]. + * + * The following fields are required: + * ```java + * .projectScoreId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectScoreId - else -> "" + /** A builder for [ProjectScoreUpdateParams]. */ + class Builder internal constructor() { + + private var projectScoreId: 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(projectScoreUpdateParams: ProjectScoreUpdateParams) = apply { + projectScoreId = projectScoreUpdateParams.projectScoreId + body = projectScoreUpdateParams.body.toBuilder() + additionalHeaders = projectScoreUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = projectScoreUpdateParams.additionalQueryParams.toBuilder() } - } - /** A project score is a user-configured score, which can be manually-labeled through the UI */ - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("categories") - @ExcludeMissing - private val categories: JsonField = JsonMissing.of(), - @JsonProperty("config") - @ExcludeMissing - private val config: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("score_type") - @ExcludeMissing - private val scoreType: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** ProjectScore id */ + fun projectScoreId(projectScoreId: String) = apply { this.projectScoreId = projectScoreId } /** - * For categorical-type project scores, the list of all categories + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [categories] + * - [config] + * - [description] + * - [name] + * - [scoreType] + * - etc. */ - fun categories(): Optional = - Optional.ofNullable(categories.getNullable("categories")) + fun body(body: Body) = apply { this.body = body.toBuilder() } - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun config(): Optional = - Optional.ofNullable(config.getNullable("config")) + /** For categorical-type project scores, the list of all categories */ + fun categories(categories: Categories?) = apply { body.categories(categories) } - /** - * Textual description of the project score - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + /** Alias for calling [Builder.categories] with `categories.orElse(null)`. */ + fun categories(categories: Optional) = categories(categories.getOrNull()) /** - * Name of the project score + * Sets [Builder.categories] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.categories] with a well-typed [Categories] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun categories(categories: JsonField) = apply { body.categories(categories) } - /** - * The type of the configured score - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun scoreType(): Optional = - Optional.ofNullable(scoreType.getNullable("score_type")) + /** Alias for calling [categories] with `Categories.ofCategorical(categorical)`. */ + fun categoriesOfCategorical(categorical: List) = apply { + body.categoriesOfCategorical(categorical) + } - /** - * Returns the raw JSON value of [categories]. - * - * Unlike [categories], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("categories") - @ExcludeMissing - fun _categories(): JsonField = categories + /** Alias for calling [categories] with `Categories.ofWeighted(weighted)`. */ + fun categories(weighted: Categories.Weighted) = apply { body.categories(weighted) } - /** - * 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 + /** Alias for calling [categories] with `Categories.ofMinimum(minimum)`. */ + fun categoriesOfMinimum(minimum: List) = apply { body.categoriesOfMinimum(minimum) } + + fun config(config: ProjectScoreConfig?) = apply { body.config(config) } + + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) /** - * Returns the raw JSON value of [description]. + * Sets [Builder.config] to an arbitrary JSON value. * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.config] with a well-typed [ProjectScoreConfig] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description + fun config(config: JsonField) = apply { body.config(config) } + + /** Textual description of the project score */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) /** - * Returns the raw JSON value of [name]. + * Sets [Builder.description] to an arbitrary JSON value. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun description(description: JsonField) = apply { body.description(description) } + + /** Name of the project score */ + fun name(name: String?) = apply { body.name(name) } + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) /** - * Returns the raw JSON value of [scoreType]. + * Sets [Builder.name] to an arbitrary JSON value. * - * Unlike [scoreType], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("score_type") - @ExcludeMissing - fun _scoreType(): JsonField = scoreType + fun name(name: JsonField) = apply { body.name(name) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** The type of the configured score */ + fun scoreType(scoreType: ProjectScoreType?) = apply { body.scoreType(scoreType) } - private var validated: Boolean = false + /** Alias for calling [Builder.scoreType] with `scoreType.orElse(null)`. */ + fun scoreType(scoreType: Optional) = scoreType(scoreType.getOrNull()) - fun validate(): Body = apply { - if (validated) { - return@apply - } + /** + * Sets [Builder.scoreType] to an arbitrary JSON value. + * + * You should usually call [Builder.scoreType] with a well-typed [ProjectScoreType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun scoreType(scoreType: JsonField) = apply { body.scoreType(scoreType) } - categories().ifPresent { it.validate() } - config().ifPresent { it.validate() } - description() - name() - scoreType() - validated = true + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) } - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Body]. */ - @JvmStatic fun builder() = Builder() + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) } - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var categories: JsonField = JsonMissing.of() - private var config: JsonField = JsonMissing.of() - private var description: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var scoreType: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - categories = body.categories - config = body.config - description = body.description - name = body.name - scoreType = body.scoreType - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** For categorical-type project scores, the list of all categories */ - fun categories(categories: Categories?) = categories(JsonField.ofNullable(categories)) - - /** Alias for calling [Builder.categories] with `categories.orElse(null)`. */ - fun categories(categories: Optional) = categories(categories.getOrNull()) - - /** - * Sets [Builder.categories] to an arbitrary JSON value. - * - * You should usually call [Builder.categories] with a well-typed [Categories] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun categories(categories: JsonField) = apply { - this.categories = categories + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - /** Alias for calling [categories] with `Categories.ofCategorical(categorical)`. */ - fun categoriesOfCategorical(categorical: List) = - categories(Categories.ofCategorical(categorical)) - - /** Alias for calling [categories] with `Categories.ofWeighted(weighted)`. */ - fun categories(weighted: Categories.Weighted) = - categories(Categories.ofWeighted(weighted)) - - /** Alias for calling [categories] with `Categories.ofMinimum(minimum)`. */ - fun categoriesOfMinimum(minimum: List) = - categories(Categories.ofMinimum(minimum)) + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun config(config: ProjectScoreConfig?) = config(JsonField.ofNullable(config)) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** Alias for calling [Builder.config] with `config.orElse(null)`. */ - fun config(config: Optional) = config(config.getOrNull()) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * Sets [Builder.config] to an arbitrary JSON value. - * - * You should usually call [Builder.config] with a well-typed [ProjectScoreConfig] 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 additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Textual description of the project score */ - fun description(description: String?) = description(JsonField.ofNullable(description)) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Name of the project score */ - fun name(name: String?) = name(JsonField.ofNullable(name)) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.name] with `name.orElse(null)`. */ - fun name(name: Optional) = name(name.getOrNull()) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * 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 replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** The type of the configured score */ - fun scoreType(scoreType: ProjectScoreType?) = scoreType(JsonField.ofNullable(scoreType)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.scoreType] with `scoreType.orElse(null)`. */ - fun scoreType(scoreType: Optional) = scoreType(scoreType.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.scoreType] to an arbitrary JSON value. - * - * You should usually call [Builder.scoreType] with a well-typed [ProjectScoreType] - * value instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun scoreType(scoreType: JsonField) = apply { - this.scoreType = scoreType - } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Body = - Body( - categories, - config, - description, - name, - scoreType, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && categories == other.categories && config == other.config && description == other.description && name == other.name && scoreType == other.scoreType && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(categories, config, description, name, scoreType, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{categories=$categories, config=$config, description=$description, name=$name, scoreType=$scoreType, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [ProjectScoreUpdateParams]. + * Returns an immutable instance of [ProjectScoreUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java * .projectScoreId() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): ProjectScoreUpdateParams = + ProjectScoreUpdateParams( + checkRequired("projectScoreId", projectScoreId), + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [ProjectScoreUpdateParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var projectScoreId: String? = null - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + fun _body(): Body = body - @JvmSynthetic - internal fun from(projectScoreUpdateParams: ProjectScoreUpdateParams) = apply { - projectScoreId = projectScoreUpdateParams.projectScoreId - body = projectScoreUpdateParams.body.toBuilder() - additionalHeaders = projectScoreUpdateParams.additionalHeaders.toBuilder() - additionalQueryParams = projectScoreUpdateParams.additionalQueryParams.toBuilder() + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectScoreId + else -> "" } - /** ProjectScore id */ - fun projectScoreId(projectScoreId: String) = apply { this.projectScoreId = projectScoreId } + override fun _headers(): Headers = additionalHeaders - /** For categorical-type project scores, the list of all categories */ - fun categories(categories: Categories?) = apply { body.categories(categories) } + override fun _queryParams(): QueryParams = additionalQueryParams - /** Alias for calling [Builder.categories] with `categories.orElse(null)`. */ - fun categories(categories: Optional) = categories(categories.getOrNull()) + /** A project score is a user-configured score, which can be manually-labeled through the UI */ + class Body + private constructor( + private val categories: JsonField, + private val config: JsonField, + private val description: JsonField, + private val name: JsonField, + private val scoreType: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("categories") + @ExcludeMissing + categories: JsonField = JsonMissing.of(), + @JsonProperty("config") + @ExcludeMissing + config: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("score_type") + @ExcludeMissing + scoreType: JsonField = JsonMissing.of(), + ) : this(categories, config, description, name, scoreType, mutableMapOf()) /** - * Sets [Builder.categories] to an arbitrary JSON value. + * For categorical-type project scores, the list of all categories * - * You should usually call [Builder.categories] with a well-typed [Categories] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun categories(categories: JsonField) = apply { body.categories(categories) } - - /** Alias for calling [categories] with `Categories.ofCategorical(categorical)`. */ - fun categoriesOfCategorical(categorical: List) = apply { - body.categoriesOfCategorical(categorical) - } - - /** Alias for calling [categories] with `Categories.ofWeighted(weighted)`. */ - fun categories(weighted: Categories.Weighted) = apply { body.categories(weighted) } - - /** Alias for calling [categories] with `Categories.ofMinimum(minimum)`. */ - fun categoriesOfMinimum(minimum: List) = apply { body.categoriesOfMinimum(minimum) } - - fun config(config: ProjectScoreConfig?) = apply { body.config(config) } + fun categories(): Optional = categories.getOptional("categories") - /** Alias for calling [Builder.config] with `config.orElse(null)`. */ - fun config(config: Optional) = config(config.getOrNull()) + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun config(): Optional = config.getOptional("config") /** - * Sets [Builder.config] to an arbitrary JSON value. + * Textual description of the project score * - * You should usually call [Builder.config] with a well-typed [ProjectScoreConfig] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun config(config: JsonField) = apply { body.config(config) } - - /** Textual description of the project score */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + fun description(): Optional = description.getOptional("description") /** - * Sets [Builder.description] to an arbitrary JSON value. + * Name of the project score * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun description(description: JsonField) = apply { body.description(description) } + fun name(): Optional = name.getOptional("name") - /** Name of the project score */ - fun name(name: String?) = apply { body.name(name) } + /** + * The type of the configured score + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun scoreType(): Optional = scoreType.getOptional("score_type") - /** Alias for calling [Builder.name] with `name.orElse(null)`. */ - fun name(name: Optional) = name(name.getOrNull()) + /** + * Returns the raw JSON value of [categories]. + * + * Unlike [categories], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("categories") + @ExcludeMissing + fun _categories(): JsonField = categories /** - * Sets [Builder.name] to an arbitrary JSON value. + * Returns the raw JSON value of [config]. * - * 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. + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. */ - fun name(name: JsonField) = apply { body.name(name) } + @JsonProperty("config") + @ExcludeMissing + fun _config(): JsonField = config - /** The type of the configured score */ - fun scoreType(scoreType: ProjectScoreType?) = apply { body.scoreType(scoreType) } + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description - /** Alias for calling [Builder.scoreType] with `scoreType.orElse(null)`. */ - fun scoreType(scoreType: Optional) = scoreType(scoreType.getOrNull()) + /** + * 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 /** - * Sets [Builder.scoreType] to an arbitrary JSON value. + * Returns the raw JSON value of [scoreType]. * - * You should usually call [Builder.scoreType] with a well-typed [ProjectScoreType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * Unlike [scoreType], this method doesn't throw if the JSON field has an unexpected type. */ - fun scoreType(scoreType: JsonField) = apply { body.scoreType(scoreType) } + @JsonProperty("score_type") + @ExcludeMissing + fun _scoreType(): JsonField = scoreType - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(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]. */ + @JvmStatic fun builder() = Builder() } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var categories: JsonField = JsonMissing.of() + private var config: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var scoreType: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + categories = body.categories + config = body.config + description = body.description + name = body.name + scoreType = body.scoreType + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** For categorical-type project scores, the list of all categories */ + fun categories(categories: Categories?) = categories(JsonField.ofNullable(categories)) + + /** Alias for calling [Builder.categories] with `categories.orElse(null)`. */ + fun categories(categories: Optional) = categories(categories.getOrNull()) + + /** + * Sets [Builder.categories] to an arbitrary JSON value. + * + * You should usually call [Builder.categories] with a well-typed [Categories] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun categories(categories: JsonField) = apply { + this.categories = categories } - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** Alias for calling [categories] with `Categories.ofCategorical(categorical)`. */ + fun categoriesOfCategorical(categorical: List) = + categories(Categories.ofCategorical(categorical)) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** Alias for calling [categories] with `Categories.ofWeighted(weighted)`. */ + fun categories(weighted: Categories.Weighted) = + categories(Categories.ofWeighted(weighted)) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** Alias for calling [categories] with `Categories.ofMinimum(minimum)`. */ + fun categoriesOfMinimum(minimum: List) = + categories(Categories.ofMinimum(minimum)) - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + fun config(config: ProjectScoreConfig?) = config(JsonField.ofNullable(config)) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [ProjectScoreConfig] 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 putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Textual description of the project score */ + fun description(description: String?) = description(JsonField.ofNullable(description)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** Name of the project score */ + fun name(name: String?) = name(JsonField.ofNullable(name)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * 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 removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + /** The type of the configured score */ + fun scoreType(scoreType: ProjectScoreType?) = scoreType(JsonField.ofNullable(scoreType)) - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + /** Alias for calling [Builder.scoreType] with `scoreType.orElse(null)`. */ + fun scoreType(scoreType: Optional) = scoreType(scoreType.getOrNull()) - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** + * Sets [Builder.scoreType] to an arbitrary JSON value. + * + * You should usually call [Builder.scoreType] with a well-typed [ProjectScoreType] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun scoreType(scoreType: JsonField) = apply { + this.scoreType = scoreType + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } - - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body( + categories, + config, + description, + name, + scoreType, + additionalProperties.toMutableMap(), + ) } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + private var validated: Boolean = false - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + fun validate(): Body = apply { + if (validated) { + return@apply } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + categories().ifPresent { it.validate() } + config().ifPresent { it.validate() } + description() + name() + scoreType().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + /** - * Returns an immutable instance of [ProjectScoreUpdateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .projectScoreId() - * ``` + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * @throws IllegalStateException if any required field is unset. + * Used for best match union deserialization. */ - fun build(): ProjectScoreUpdateParams = - ProjectScoreUpdateParams( - checkRequired("projectScoreId", projectScoreId), - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + @JvmSynthetic + internal fun validity(): Int = + (categories.asKnown().getOrNull()?.validity() ?: 0) + + (config.asKnown().getOrNull()?.validity() ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (scoreType.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && categories == other.categories && config == other.config && description == other.description && name == other.name && scoreType == other.scoreType && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(categories, config, description, name, scoreType, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{categories=$categories, config=$config, description=$description, name=$name, scoreType=$scoreType, additionalProperties=$additionalProperties}" } /** For categorical-type project scores, the list of all categories */ @@ -735,14 +775,13 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { categorical != null -> visitor.visitCategorical(categorical) weighted != null -> visitor.visitWeighted(weighted) minimum != null -> visitor.visitMinimum(minimum) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -767,6 +806,35 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitCategorical(categorical: List) = + categorical.sumOf { it.validity().toInt() } + + override fun visitWeighted(weighted: Weighted) = weighted.validity() + + override fun visitMinimum(minimum: List) = minimum.size + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -834,21 +902,30 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Categories { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef>()) { - it.forEach { it.validate() } - } - ?.let { - return Categories(categorical = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Categories(weighted = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Categories(minimum = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Categories(weighted = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef>()) + ?.let { Categories(categorical = it, _json = json) }, + tryDeserialize(node, jacksonTypeRef>())?.let { + Categories(minimum = 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 -> Categories(_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 Categories(_json = json) } } @@ -870,28 +947,17 @@ private constructor( } /** For weighted-type project scores, the weights of each score */ - @NoAutoDetect class Weighted @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Weighted = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -940,6 +1006,34 @@ private constructor( fun build(): Weighted = Weighted(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Weighted = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectSettings.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectSettings.kt index 57bc8590..474d6826 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectSettings.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectSettings.kt @@ -7,36 +7,40 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 -@NoAutoDetect class ProjectSettings -@JsonCreator private constructor( - @JsonProperty("baseline_experiment_id") - @ExcludeMissing - private val baselineExperimentId: JsonField = JsonMissing.of(), - @JsonProperty("comparison_key") - @ExcludeMissing - private val comparisonKey: JsonField = JsonMissing.of(), - @JsonProperty("spanFieldOrder") - @ExcludeMissing - private val spanFieldOrder: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val baselineExperimentId: JsonField, + private val comparisonKey: JsonField, + private val spanFieldOrder: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("baseline_experiment_id") + @ExcludeMissing + baselineExperimentId: JsonField = JsonMissing.of(), + @JsonProperty("comparison_key") + @ExcludeMissing + comparisonKey: JsonField = JsonMissing.of(), + @JsonProperty("spanFieldOrder") + @ExcludeMissing + spanFieldOrder: JsonField> = JsonMissing.of(), + ) : this(baselineExperimentId, comparisonKey, spanFieldOrder, mutableMapOf()) + /** * The id of the experiment to use as the default baseline for comparisons * @@ -44,7 +48,7 @@ private constructor( * server responded with an unexpected value). */ fun baselineExperimentId(): Optional = - Optional.ofNullable(baselineExperimentId.getNullable("baseline_experiment_id")) + baselineExperimentId.getOptional("baseline_experiment_id") /** * The key used to join two experiments (defaults to `input`) @@ -52,8 +56,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun comparisonKey(): Optional = - Optional.ofNullable(comparisonKey.getNullable("comparison_key")) + fun comparisonKey(): Optional = comparisonKey.getOptional("comparison_key") /** * The order of the fields to display in the trace view @@ -62,7 +65,7 @@ private constructor( * server responded with an unexpected value). */ fun spanFieldOrder(): Optional> = - Optional.ofNullable(spanFieldOrder.getNullable("spanFieldOrder")) + spanFieldOrder.getOptional("spanFieldOrder") /** * Returns the raw JSON value of [baselineExperimentId]. @@ -92,22 +95,15 @@ private constructor( @ExcludeMissing fun _spanFieldOrder(): JsonField> = spanFieldOrder + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ProjectSettings = apply { - if (validated) { - return@apply - } - - baselineExperimentId() - comparisonKey() - spanFieldOrder().ifPresent { it.forEach { it.validate() } } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -234,30 +230,65 @@ private constructor( baselineExperimentId, comparisonKey, (spanFieldOrder ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): ProjectSettings = apply { + if (validated) { + return@apply + } + + baselineExperimentId() + comparisonKey() + spanFieldOrder().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (baselineExperimentId.asKnown().isPresent) 1 else 0) + + (if (comparisonKey.asKnown().isPresent) 1 else 0) + + (spanFieldOrder.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + class SpanFieldOrder - @JsonCreator private constructor( - @JsonProperty("column_id") - @ExcludeMissing - private val columnId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("position") - @ExcludeMissing - private val position: JsonField = JsonMissing.of(), - @JsonProperty("layout") - @ExcludeMissing - private val layout: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val columnId: JsonField, + private val objectType: JsonField, + private val position: JsonField, + private val layout: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("column_id") + @ExcludeMissing + columnId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("position") + @ExcludeMissing + position: JsonField = JsonMissing.of(), + @JsonProperty("layout") @ExcludeMissing layout: JsonField = JsonMissing.of(), + ) : this(columnId, objectType, position, layout, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected value). @@ -280,7 +311,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun layout(): Optional = Optional.ofNullable(layout.getNullable("layout")) + fun layout(): Optional = layout.getOptional("layout") /** * Returns the raw JSON value of [columnId]. @@ -312,23 +343,15 @@ private constructor( */ @JsonProperty("layout") @ExcludeMissing fun _layout(): JsonField = layout + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SpanFieldOrder = apply { - if (validated) { - return@apply - } - - columnId() - objectType() - position() - layout() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -451,10 +474,45 @@ private constructor( checkRequired("objectType", objectType), checkRequired("position", position), layout, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): SpanFieldOrder = apply { + if (validated) { + return@apply + } + + columnId() + objectType() + position() + layout().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (columnId.asKnown().isPresent) 1 else 0) + + (if (objectType.asKnown().isPresent) 1 else 0) + + (if (position.asKnown().isPresent) 1 else 0) + + (layout.asKnown().getOrNull()?.validity() ?: 0) + class Layout @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -544,6 +602,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Layout = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTag.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTag.kt index 180ffb4e..b97d8d90 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTag.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTag.kt @@ -6,16 +6,14 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -24,28 +22,33 @@ import kotlin.jvm.optionals.getOrNull * A project tag is a user-configured tag for tracking and filtering your experiments, logs, and * other data */ -@NoAutoDetect class ProjectTag -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonProperty("color") @ExcludeMissing private val color: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val name: JsonField, + private val projectId: JsonField, + private val userId: JsonField, + private val color: JsonField, + private val created: JsonField, + private val description: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") @ExcludeMissing projectId: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + @JsonProperty("color") @ExcludeMissing color: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + ) : this(id, name, projectId, userId, color, created, description, mutableMapOf()) + /** * Unique identifier for the project tag * @@ -82,7 +85,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun color(): Optional = Optional.ofNullable(color.getNullable("color")) + fun color(): Optional = color.getOptional("color") /** * Date of project tag creation @@ -90,7 +93,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Textual description of the project tag @@ -98,8 +101,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun description(): Optional = description.getOptional("description") /** * Returns the raw JSON value of [id]. @@ -150,26 +152,15 @@ private constructor( */ @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ProjectTag = apply { - if (validated) { - return@apply - } - - id() - name() - projectId() - userId() - color() - created() - description() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -344,10 +335,50 @@ private constructor( color, created, description, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): ProjectTag = apply { + if (validated) { + return@apply + } + + id() + name() + projectId() + userId() + color() + created() + description() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + (if (color.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagCreateParams.kt index ddb134a6..c6346741 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagCreateParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -99,32 +97,265 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ProjectTagCreateParams]. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectTagCreateParams]. */ + 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(projectTagCreateParams: ProjectTagCreateParams) = apply { + body = projectTagCreateParams.body.toBuilder() + additionalHeaders = projectTagCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = projectTagCreateParams.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: + * - [name] + * - [projectId] + * - [color] + * - [description] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the project tag */ + fun name(name: String) = apply { body.name(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 { body.name(name) } + + /** Unique identifier for the project that the project tag belongs under */ + fun projectId(projectId: String) = apply { body.projectId(projectId) } + + /** + * Sets [Builder.projectId] to an arbitrary JSON value. + * + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } + + /** Color of the tag for the UI */ + fun color(color: String?) = apply { body.color(color) } + + /** Alias for calling [Builder.color] with `color.orElse(null)`. */ + fun color(color: Optional) = color(color.getOrNull()) + + /** + * Sets [Builder.color] to an arbitrary JSON value. + * + * You should usually call [Builder.color] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun color(color: JsonField) = apply { body.color(color) } + + /** Textual description of the project tag */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { body.description(description) } + + 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 [ProjectTagCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectTagCreateParams = + ProjectTagCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body override fun _headers(): Headers = additionalHeaders override fun _queryParams(): QueryParams = additionalQueryParams - @NoAutoDetect class Body - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("color") - @ExcludeMissing - private val color: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val projectId: JsonField, + private val color: JsonField, + private val description: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") + @ExcludeMissing + projectId: JsonField = JsonMissing.of(), + @JsonProperty("color") @ExcludeMissing color: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + ) : this(name, projectId, color, description, mutableMapOf()) + /** * Name of the project tag * @@ -147,7 +378,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun color(): Optional = Optional.ofNullable(color.getNullable("color")) + fun color(): Optional = color.getOptional("color") /** * Textual description of the project tag @@ -155,8 +386,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun description(): Optional = description.getOptional("description") /** * Returns the raw JSON value of [name]. @@ -188,23 +418,15 @@ private constructor( @ExcludeMissing fun _description(): JsonField = description + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - name() - projectId() - color() - description() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -334,247 +556,61 @@ private constructor( checkRequired("projectId", projectId), color, description, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply } - return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && color == other.color && description == other.description && additionalProperties == other.additionalProperties /* spotless:on */ + name() + projectId() + color() + description() + validated = true } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, projectId, color, description, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{name=$name, projectId=$projectId, color=$color, description=$description, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } /** - * Returns a mutable builder for constructing an instance of [ProjectTagCreateParams]. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * The following fields are required: - * ```java - * .name() - * .projectId() - * ``` + * Used for best match union deserialization. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ProjectTagCreateParams]. */ - @NoAutoDetect - 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(projectTagCreateParams: ProjectTagCreateParams) = apply { - body = projectTagCreateParams.body.toBuilder() - additionalHeaders = projectTagCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = projectTagCreateParams.additionalQueryParams.toBuilder() - } - - /** Name of the project tag */ - fun name(name: String) = apply { body.name(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 { body.name(name) } - - /** Unique identifier for the project that the project tag belongs under */ - fun projectId(projectId: String) = apply { body.projectId(projectId) } - - /** - * Sets [Builder.projectId] to an arbitrary JSON value. - * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } - - /** Color of the tag for the UI */ - fun color(color: String?) = apply { body.color(color) } - - /** Alias for calling [Builder.color] with `color.orElse(null)`. */ - fun color(color: Optional) = color(color.getOrNull()) - - /** - * Sets [Builder.color] to an arbitrary JSON value. - * - * You should usually call [Builder.color] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun color(color: JsonField) = apply { body.color(color) } - - /** Textual description of the project tag */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun description(description: JsonField) = apply { body.description(description) } - - 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) - } + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (color.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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) + return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && color == other.color && description == other.description && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, projectId, color, description, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [ProjectTagCreateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): ProjectTagCreateParams = - ProjectTagCreateParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{name=$name, projectId=$projectId, color=$color, description=$description, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagDeleteParams.kt index 9e495e9a..bf7c316a 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagDeleteParams.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,26 +23,11 @@ private constructor( /** ProjectTag id */ fun projectTagId(): String = projectTagId - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectTagId - else -> "" - } - } + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -61,7 +45,6 @@ private constructor( } /** A builder for [ProjectTagDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var projectTagId: String? = null @@ -222,6 +205,19 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectTagId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListPage.kt index 59ff4610..6180b9a9 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListPage.kt @@ -2,171 +2,115 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.ProjectTagService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all project_tags. The project_tags are sorted by creation date, with the most - * recently-created project_tags coming first - */ +/** @see [ProjectTagService.list] */ class ProjectTagListPage private constructor( - private val projectTagsService: ProjectTagService, + private val service: ProjectTagService, private val params: ProjectTagListParams, - private val response: Response, + private val response: ProjectTagListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [ProjectTagListPageResponse], but gracefully handles missing data. + * + * @see [ProjectTagListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ProjectTagListPage && projectTagsService == other.projectTagsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(projectTagsService, params, response) /* spotless:on */ - - override fun toString() = - "ProjectTagListPage{projectTagsService=$projectTagsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - ProjectTagListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - ProjectTagListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { projectTagsService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of( - projectTagsService: ProjectTagService, - params: ProjectTagListParams, - response: Response, - ) = ProjectTagListPage(projectTagsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") - private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): ProjectTagListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): ProjectTagListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [ProjectTagListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [ProjectTagListPage]. */ + class Builder internal constructor() { - companion object { + private var service: ProjectTagService? = null + private var params: ProjectTagListParams? = null + private var response: ProjectTagListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [ProjectTagListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(projectTagListPage: ProjectTagListPage) = apply { + service = projectTagListPage.service + params = projectTagListPage.params + response = projectTagListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: ProjectTagService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: ProjectTagListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ProjectTagListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ProjectTagListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectTagListPage = + ProjectTagListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: ProjectTagListPage) : Iterable { @@ -187,4 +131,17 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ProjectTagListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "ProjectTagListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListPageAsync.kt index d7ff05b7..26fc37ac 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListPageAsync.kt @@ -2,175 +2,119 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.ProjectTagServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all project_tags. The project_tags are sorted by creation date, with the most - * recently-created project_tags coming first - */ +/** @see [ProjectTagServiceAsync.list] */ class ProjectTagListPageAsync private constructor( - private val projectTagsService: ProjectTagServiceAsync, + private val service: ProjectTagServiceAsync, private val params: ProjectTagListParams, - private val response: Response, + private val response: ProjectTagListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [ProjectTagListPageResponse], but gracefully handles missing data. + * + * @see [ProjectTagListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ProjectTagListPageAsync && projectTagsService == other.projectTagsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(projectTagsService, params, response) /* spotless:on */ - - override fun toString() = - "ProjectTagListPageAsync{projectTagsService=$projectTagsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - ProjectTagListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - ProjectTagListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { projectTagsService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of( - projectTagsService: ProjectTagServiceAsync, - params: ProjectTagListParams, - response: Response, - ) = ProjectTagListPageAsync(projectTagsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") - private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): ProjectTagListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): ProjectTagListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [ProjectTagListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [ProjectTagListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: ProjectTagServiceAsync? = null + private var params: ProjectTagListParams? = null + private var response: ProjectTagListPageResponse? = null - /** - * Returns a mutable builder for constructing an instance of [ProjectTagListPageAsync]. - */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(projectTagListPageAsync: ProjectTagListPageAsync) = apply { + service = projectTagListPageAsync.service + params = projectTagListPageAsync.params + response = projectTagListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: ProjectTagServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: ProjectTagListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ProjectTagListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ProjectTagListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectTagListPageAsync = + ProjectTagListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: ProjectTagListPageAsync) { @@ -198,4 +142,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ProjectTagListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "ProjectTagListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListPageResponse.kt new file mode 100644 index 00000000..b50ad2b4 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListPageResponse.kt @@ -0,0 +1,194 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class ProjectTagListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") + @ExcludeMissing + objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of project_tag objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [ProjectTagListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectTagListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(projectTagListPageResponse: ProjectTagListPageResponse) = apply { + objects = projectTagListPageResponse.objects.map { it.toMutableList() } + additionalProperties = projectTagListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of project_tag objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [ProjectTag] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: ProjectTag) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ProjectTagListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectTagListPageResponse = + ProjectTagListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ProjectTagListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ProjectTagListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProjectTagListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListParams.kt index 9bc9a039..d24144b0 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListParams.kt @@ -2,22 +2,10 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -83,33 +71,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - endingBefore?.let { put("ending_before", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - orgName?.let { put("org_name", it) } - projectId?.let { put("project_id", it) } - projectName?.let { put("project_name", it) } - projectTagName?.let { put("project_tag_name", it) } - startingAfter?.let { put("starting_after", it) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -121,7 +82,6 @@ private constructor( } /** A builder for [ProjectTagListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var endingBefore: String? = null @@ -345,17 +305,41 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + endingBefore?.let { put("ending_before", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + orgName?.let { put("org_name", it) } + projectId?.let { put("project_id", it) } + projectName?.let { put("project_name", it) } + projectTagName?.let { put("project_tag_name", it) } + startingAfter?.let { put("starting_after", it) } + putAll(additionalQueryParams) + } + .build() + /** * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -370,15 +354,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -394,7 +375,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -411,51 +391,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagReplaceParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagReplaceParams.kt index d4b0801e..3b1cb3fd 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagReplaceParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagReplaceParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -100,32 +98,265 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ProjectTagReplaceParams]. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectTagReplaceParams]. */ + 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(projectTagReplaceParams: ProjectTagReplaceParams) = apply { + body = projectTagReplaceParams.body.toBuilder() + additionalHeaders = projectTagReplaceParams.additionalHeaders.toBuilder() + additionalQueryParams = projectTagReplaceParams.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: + * - [name] + * - [projectId] + * - [color] + * - [description] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the project tag */ + fun name(name: String) = apply { body.name(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 { body.name(name) } + + /** Unique identifier for the project that the project tag belongs under */ + fun projectId(projectId: String) = apply { body.projectId(projectId) } + + /** + * Sets [Builder.projectId] to an arbitrary JSON value. + * + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } + + /** Color of the tag for the UI */ + fun color(color: String?) = apply { body.color(color) } + + /** Alias for calling [Builder.color] with `color.orElse(null)`. */ + fun color(color: Optional) = color(color.getOrNull()) + + /** + * Sets [Builder.color] to an arbitrary JSON value. + * + * You should usually call [Builder.color] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun color(color: JsonField) = apply { body.color(color) } + + /** Textual description of the project tag */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { body.description(description) } + + 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 [ProjectTagReplaceParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectTagReplaceParams = + ProjectTagReplaceParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body override fun _headers(): Headers = additionalHeaders override fun _queryParams(): QueryParams = additionalQueryParams - @NoAutoDetect class Body - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("color") - @ExcludeMissing - private val color: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val projectId: JsonField, + private val color: JsonField, + private val description: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") + @ExcludeMissing + projectId: JsonField = JsonMissing.of(), + @JsonProperty("color") @ExcludeMissing color: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + ) : this(name, projectId, color, description, mutableMapOf()) + /** * Name of the project tag * @@ -148,7 +379,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun color(): Optional = Optional.ofNullable(color.getNullable("color")) + fun color(): Optional = color.getOptional("color") /** * Textual description of the project tag @@ -156,8 +387,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun description(): Optional = description.getOptional("description") /** * Returns the raw JSON value of [name]. @@ -189,23 +419,15 @@ private constructor( @ExcludeMissing fun _description(): JsonField = description + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - name() - projectId() - color() - description() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -335,247 +557,61 @@ private constructor( checkRequired("projectId", projectId), color, description, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply } - return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && color == other.color && description == other.description && additionalProperties == other.additionalProperties /* spotless:on */ + name() + projectId() + color() + description() + validated = true } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, projectId, color, description, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{name=$name, projectId=$projectId, color=$color, description=$description, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } /** - * Returns a mutable builder for constructing an instance of [ProjectTagReplaceParams]. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * The following fields are required: - * ```java - * .name() - * .projectId() - * ``` + * Used for best match union deserialization. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ProjectTagReplaceParams]. */ - @NoAutoDetect - 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(projectTagReplaceParams: ProjectTagReplaceParams) = apply { - body = projectTagReplaceParams.body.toBuilder() - additionalHeaders = projectTagReplaceParams.additionalHeaders.toBuilder() - additionalQueryParams = projectTagReplaceParams.additionalQueryParams.toBuilder() - } - - /** Name of the project tag */ - fun name(name: String) = apply { body.name(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 { body.name(name) } - - /** Unique identifier for the project that the project tag belongs under */ - fun projectId(projectId: String) = apply { body.projectId(projectId) } - - /** - * Sets [Builder.projectId] to an arbitrary JSON value. - * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } - - /** Color of the tag for the UI */ - fun color(color: String?) = apply { body.color(color) } - - /** Alias for calling [Builder.color] with `color.orElse(null)`. */ - fun color(color: Optional) = color(color.getOrNull()) - - /** - * Sets [Builder.color] to an arbitrary JSON value. - * - * You should usually call [Builder.color] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun color(color: JsonField) = apply { body.color(color) } - - /** Textual description of the project tag */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun description(description: JsonField) = apply { body.description(description) } - - 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) - } + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (color.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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) + return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && color == other.color && description == other.description && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, projectId, color, description, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [ProjectTagReplaceParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): ProjectTagReplaceParams = - ProjectTagReplaceParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{name=$name, projectId=$projectId, color=$color, description=$description, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagRetrieveParams.kt index 36ea7037..20c3485b 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectTagId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [ProjectTagRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var projectTagId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectTagId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagUpdateParams.kt index 6a457c6e..9f4bcf04 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagUpdateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagUpdateParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -89,217 +87,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectTagId - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("color") - @ExcludeMissing - private val color: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * Color of the tag for the UI - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun color(): Optional = Optional.ofNullable(color.getNullable("color")) - - /** - * Textual description of the project tag - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - /** - * Name of the project tag - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** - * Returns the raw JSON value of [color]. - * - * Unlike [color], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("color") @ExcludeMissing fun _color(): JsonField = color - - /** - * Returns the raw JSON value of [description]. - * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description - - /** - * Returns the raw JSON value of [name]. - * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - color() - description() - name() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Body]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var color: JsonField = JsonMissing.of() - private var description: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - color = body.color - description = body.description - name = body.name - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** Color of the tag for the UI */ - fun color(color: String?) = color(JsonField.ofNullable(color)) - - /** Alias for calling [Builder.color] with `color.orElse(null)`. */ - fun color(color: Optional) = color(color.getOrNull()) - - /** - * Sets [Builder.color] to an arbitrary JSON value. - * - * You should usually call [Builder.color] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun color(color: JsonField) = apply { this.color = color } - - /** Textual description of the project tag */ - fun description(description: String?) = description(JsonField.ofNullable(description)) - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } - - /** Name of the project tag */ - 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 additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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. - */ - fun build(): Body = Body(color, description, name, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && color == other.color && description == other.description && name == other.name && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(color, description, name, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{color=$color, description=$description, name=$name, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -316,7 +103,6 @@ private constructor( } /** A builder for [ProjectTagUpdateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var projectTagId: String? = null @@ -335,6 +121,17 @@ private constructor( /** ProjectTag id */ fun projectTagId(projectTagId: String) = apply { this.projectTagId = projectTagId } + /** + * 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: + * - [color] + * - [description] + * - [name] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** Color of the tag for the UI */ fun color(color: String?) = apply { body.color(color) } @@ -516,6 +313,241 @@ private constructor( ) } + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectTagId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val color: JsonField, + private val description: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("color") @ExcludeMissing color: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(color, description, name, mutableMapOf()) + + /** + * Color of the tag for the UI + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun color(): Optional = color.getOptional("color") + + /** + * Textual description of the project tag + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * Name of the project tag + * + * @throws BraintrustInvalidDataException 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 [color]. + * + * Unlike [color], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("color") @ExcludeMissing fun _color(): JsonField = color + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var color: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + color = body.color + description = body.description + name = body.name + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Color of the tag for the UI */ + fun color(color: String?) = color(JsonField.ofNullable(color)) + + /** Alias for calling [Builder.color] with `color.orElse(null)`. */ + fun color(color: Optional) = color(color.getOrNull()) + + /** + * Sets [Builder.color] to an arbitrary JSON value. + * + * You should usually call [Builder.color] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun color(color: JsonField) = apply { this.color = color } + + /** Textual description of the project tag */ + fun description(description: String?) = description(JsonField.ofNullable(description)) + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + + /** Name of the project tag */ + 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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. + */ + fun build(): Body = Body(color, description, name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + color() + description() + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (color.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && color == other.color && description == other.description && name == other.name && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(color, description, name, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{color=$color, description=$description, name=$name, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectUpdateParams.kt index 3c6ecfc1..b97b8926 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectUpdateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectUpdateParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -75,183 +73,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectId - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("settings") - @ExcludeMissing - private val settings: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * Name of the project - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** - * Project settings. Patch operations replace all settings, so make sure you include all - * settings you want to keep. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun settings(): Optional = - Optional.ofNullable(settings.getNullable("settings")) - - /** - * 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 [settings]. - * - * Unlike [settings], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("settings") - @ExcludeMissing - fun _settings(): JsonField = settings - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - name() - settings().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Body]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var name: JsonField = JsonMissing.of() - private var settings: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - settings = body.settings - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** Name of the project */ - 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 } - - /** - * Project settings. Patch operations replace all settings, so make sure you include all - * settings you want to keep. - */ - fun settings(settings: ProjectSettings?) = settings(JsonField.ofNullable(settings)) - - /** Alias for calling [Builder.settings] with `settings.orElse(null)`. */ - fun settings(settings: Optional) = settings(settings.getOrNull()) - - /** - * Sets [Builder.settings] to an arbitrary JSON value. - * - * You should usually call [Builder.settings] with a well-typed [ProjectSettings] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun settings(settings: JsonField) = apply { this.settings = settings } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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. - */ - fun build(): Body = Body(name, settings, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && name == other.name && settings == other.settings && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, settings, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{name=$name, settings=$settings, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -268,7 +89,6 @@ private constructor( } /** A builder for [ProjectUpdateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var projectId: String? = null @@ -287,6 +107,16 @@ private constructor( /** Project id */ fun projectId(projectId: String) = apply { this.projectId = projectId } + /** + * 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: + * - [name] + * - [settings] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** Name of the project */ fun name(name: String?) = apply { body.name(name) } @@ -457,6 +287,207 @@ private constructor( ) } + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val name: JsonField, + private val settings: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("settings") + @ExcludeMissing + settings: JsonField = JsonMissing.of(), + ) : this(name, settings, mutableMapOf()) + + /** + * Name of the project + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Project settings. Patch operations replace all settings, so make sure you include all + * settings you want to keep. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun settings(): Optional = settings.getOptional("settings") + + /** + * 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 [settings]. + * + * Unlike [settings], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("settings") + @ExcludeMissing + fun _settings(): JsonField = settings + + @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]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField = JsonMissing.of() + private var settings: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + settings = body.settings + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the project */ + 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 } + + /** + * Project settings. Patch operations replace all settings, so make sure you include all + * settings you want to keep. + */ + fun settings(settings: ProjectSettings?) = settings(JsonField.ofNullable(settings)) + + /** Alias for calling [Builder.settings] with `settings.orElse(null)`. */ + fun settings(settings: Optional) = settings(settings.getOrNull()) + + /** + * Sets [Builder.settings] to an arbitrary JSON value. + * + * You should usually call [Builder.settings] with a well-typed [ProjectSettings] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun settings(settings: JsonField) = apply { this.settings = settings } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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. + */ + fun build(): Body = Body(name, settings, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + settings().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (settings.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && name == other.name && settings == other.settings && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, settings, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, settings=$settings, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Prompt.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Prompt.kt index aa64928b..9157056c 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Prompt.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Prompt.kt @@ -7,10 +7,8 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -18,46 +16,69 @@ import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class Prompt -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("_xact_id") - @ExcludeMissing - private val _xactId: JsonField = JsonMissing.of(), - @JsonProperty("log_id") @ExcludeMissing private val logId: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("org_id") @ExcludeMissing private val orgId: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("slug") @ExcludeMissing private val slug: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("function_type") - @ExcludeMissing - private val functionType: JsonField = JsonMissing.of(), - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonProperty("prompt_data") - @ExcludeMissing - private val promptData: JsonField = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val _xactId: JsonField, + private val logId: JsonField, + private val name: JsonField, + private val orgId: JsonField, + private val projectId: JsonField, + private val slug: JsonField, + private val created: JsonField, + private val description: JsonField, + private val functionType: JsonField, + private val metadata: JsonField, + private val promptData: JsonField, + private val tags: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("_xact_id") @ExcludeMissing _xactId: JsonField = JsonMissing.of(), + @JsonProperty("log_id") @ExcludeMissing logId: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("org_id") @ExcludeMissing orgId: JsonField = JsonMissing.of(), + @JsonProperty("project_id") @ExcludeMissing projectId: JsonField = JsonMissing.of(), + @JsonProperty("slug") @ExcludeMissing slug: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("function_type") + @ExcludeMissing + functionType: JsonField = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("prompt_data") + @ExcludeMissing + promptData: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this( + id, + _xactId, + logId, + name, + orgId, + projectId, + slug, + created, + description, + functionType, + metadata, + promptData, + tags, + mutableMapOf(), + ) + /** * Unique identifier for the prompt * @@ -122,7 +143,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Textual description of the prompt @@ -130,15 +151,13 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun description(): Optional = description.getOptional("description") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun functionType(): Optional = - Optional.ofNullable(functionType.getNullable("function_type")) + fun functionType(): Optional = functionType.getOptional("function_type") /** * User-controlled metadata about the prompt @@ -146,7 +165,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** * The prompt, model, and its parameters @@ -154,8 +173,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun promptData(): Optional = - Optional.ofNullable(promptData.getNullable("prompt_data")) + fun promptData(): Optional = promptData.getOptional("prompt_data") /** * A list of tags for the prompt @@ -163,7 +181,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * Returns the raw JSON value of [id]. @@ -260,32 +278,15 @@ private constructor( */ @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Prompt = apply { - if (validated) { - return@apply - } - - id() - _xactId() - logId() - name() - orgId() - projectId() - slug() - created() - description() - functionType() - metadata().ifPresent { it.validate() } - promptData().ifPresent { it.validate() } - tags() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -582,10 +583,62 @@ private constructor( metadata, promptData, (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Prompt = apply { + if (validated) { + return@apply + } + + id() + _xactId() + logId().validate() + name() + orgId() + projectId() + slug() + created() + description() + functionType().ifPresent { it.validate() } + metadata().ifPresent { it.validate() } + promptData().ifPresent { it.validate() } + tags() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (_xactId.asKnown().isPresent) 1 else 0) + + (logId.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (orgId.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (slug.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (functionType.asKnown().getOrNull()?.validity() ?: 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (promptData.asKnown().getOrNull()?.validity() ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + /** A literal 'p' which identifies the object as a project prompt */ class LogId @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -668,6 +721,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): LogId = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -783,6 +863,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): FunctionType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -797,28 +904,17 @@ private constructor( } /** User-controlled metadata about the prompt */ - @NoAutoDetect class Metadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -864,6 +960,34 @@ private constructor( 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: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptCreateParams.kt index a7e0dcef..b631e3b1 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptCreateParams.kt @@ -7,19 +7,18 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -144,401 +143,275 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun toBuilder() = Builder().from(this) - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("slug") - @ExcludeMissing - private val slug: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("function_type") - @ExcludeMissing - private val functionType: JsonField = JsonMissing.of(), - @JsonProperty("prompt_data") - @ExcludeMissing - private val promptData: JsonField = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + companion object { /** - * Name of the prompt + * Returns a mutable builder for constructing an instance of [PromptCreateParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .name() + * .projectId() + * .slug() + * ``` */ - fun name(): String = name.getRequired("name") + @JvmStatic fun builder() = Builder() + } - /** - * Unique identifier for the project that the prompt belongs under - * - * @throws BraintrustInvalidDataException 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 projectId(): String = projectId.getRequired("project_id") + /** A builder for [PromptCreateParams]. */ + class Builder internal constructor() { - /** - * Unique identifier for the prompt - * - * @throws BraintrustInvalidDataException 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 slug(): String = slug.getRequired("slug") + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - /** - * Textual description of the prompt - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + @JvmSynthetic + internal fun from(promptCreateParams: PromptCreateParams) = apply { + body = promptCreateParams.body.toBuilder() + additionalHeaders = promptCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = promptCreateParams.additionalQueryParams.toBuilder() + } /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [name] + * - [projectId] + * - [slug] + * - [description] + * - [functionType] + * - etc. */ - fun functionType(): Optional = - Optional.ofNullable(functionType.getNullable("function_type")) + fun body(body: Body) = apply { this.body = body.toBuilder() } - /** - * The prompt, model, and its parameters - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun promptData(): Optional = - Optional.ofNullable(promptData.getNullable("prompt_data")) + /** Name of the prompt */ + fun name(name: String) = apply { body.name(name) } /** - * A list of tags for the prompt + * Sets [Builder.name] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected 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 tags(): Optional> = Optional.ofNullable(tags.getNullable("tags")) + fun name(name: JsonField) = apply { body.name(name) } + + /** Unique identifier for the project that the prompt belongs under */ + fun projectId(projectId: String) = apply { body.projectId(projectId) } /** - * Returns the raw JSON value of [name]. + * Sets [Builder.projectId] to an arbitrary JSON value. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } + + /** Unique identifier for the prompt */ + fun slug(slug: String) = apply { body.slug(slug) } /** - * Returns the raw JSON value of [projectId]. + * Sets [Builder.slug] to an arbitrary JSON value. * - * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.slug] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId + fun slug(slug: JsonField) = apply { body.slug(slug) } + + /** Textual description of the prompt */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) /** - * Returns the raw JSON value of [slug]. + * Sets [Builder.description] to an arbitrary JSON value. * - * Unlike [slug], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("slug") @ExcludeMissing fun _slug(): JsonField = slug + fun description(description: JsonField) = apply { body.description(description) } + + fun functionType(functionType: FunctionType?) = apply { body.functionType(functionType) } + + /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ + fun functionType(functionType: Optional) = + functionType(functionType.getOrNull()) /** - * Returns the raw JSON value of [description]. + * Sets [Builder.functionType] to an arbitrary JSON value. * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.functionType] with a well-typed [FunctionType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description + fun functionType(functionType: JsonField) = apply { + body.functionType(functionType) + } + + /** The prompt, model, and its parameters */ + fun promptData(promptData: PromptData?) = apply { body.promptData(promptData) } + + /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ + fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) /** - * Returns the raw JSON value of [functionType]. + * Sets [Builder.promptData] to an arbitrary JSON value. * - * Unlike [functionType], this method doesn't throw if the JSON field has an unexpected - * type. + * You should usually call [Builder.promptData] with a well-typed [PromptData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("function_type") - @ExcludeMissing - fun _functionType(): JsonField = functionType + fun promptData(promptData: JsonField) = apply { body.promptData(promptData) } + + /** A list of tags for the prompt */ + fun tags(tags: List?) = apply { body.tags(tags) } + + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) /** - * Returns the raw JSON value of [promptData]. + * Sets [Builder.tags] to an arbitrary JSON value. * - * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.tags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("prompt_data") - @ExcludeMissing - fun _promptData(): JsonField = promptData + fun tags(tags: JsonField>) = apply { body.tags(tags) } /** - * Returns the raw JSON value of [tags]. + * Adds a single [String] to [tags]. * - * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + fun addTag(tag: String) = apply { body.addTag(tag) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var validated: Boolean = false + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - fun validate(): Body = apply { - if (validated) { - return@apply + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - name() - projectId() - slug() - description() - functionType() - promptData().ifPresent { it.validate() } - tags() - validated = true - } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun toBuilder() = Builder().from(this) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - companion object { + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .slug() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - private var name: JsonField? = null - private var projectId: JsonField? = null - private var slug: JsonField? = null - private var description: JsonField = JsonMissing.of() - private var functionType: JsonField = JsonMissing.of() - private var promptData: JsonField = JsonMissing.of() - private var tags: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - projectId = body.projectId - slug = body.slug - description = body.description - functionType = body.functionType - promptData = body.promptData - tags = body.tags.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Name of the prompt */ - fun name(name: String) = name(JsonField.of(name)) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** - * 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 } - - /** Unique identifier for the project that the prompt belongs under */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - - /** - * Sets [Builder.projectId] to an arbitrary JSON value. - * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } - - /** Unique identifier for the prompt */ - fun slug(slug: String) = slug(JsonField.of(slug)) - - /** - * Sets [Builder.slug] to an arbitrary JSON value. - * - * You should usually call [Builder.slug] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun slug(slug: JsonField) = apply { this.slug = slug } - - /** Textual description of the prompt */ - fun description(description: String?) = description(JsonField.ofNullable(description)) - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } - - fun functionType(functionType: FunctionType?) = - functionType(JsonField.ofNullable(functionType)) - - /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ - fun functionType(functionType: Optional) = - functionType(functionType.getOrNull()) - - /** - * Sets [Builder.functionType] to an arbitrary JSON value. - * - * You should usually call [Builder.functionType] with a well-typed [FunctionType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun functionType(functionType: JsonField) = apply { - this.functionType = functionType - } - - /** The prompt, model, and its parameters */ - fun promptData(promptData: PromptData?) = promptData(JsonField.ofNullable(promptData)) - - /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ - fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) - - /** - * Sets [Builder.promptData] to an arbitrary JSON value. - * - * You should usually call [Builder.promptData] with a well-typed [PromptData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun promptData(promptData: JsonField) = apply { - this.promptData = promptData - } + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** A list of tags for the prompt */ - fun tags(tags: List?) = tags(JsonField.ofNullable(tags)) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ - fun tags(tags: Optional>) = tags(tags.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.tags] to an arbitrary JSON value. - * - * You should usually call [Builder.tags] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun tags(tags: JsonField>) = apply { - this.tags = tags.map { it.toMutableList() } - } + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Adds a single [String] to [tags]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addTag(tag: String) = apply { - tags = - (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } - } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .slug() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("name", name), - checkRequired("projectId", projectId), - checkRequired("slug", slug), - description, - functionType, - promptData, - (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && slug == other.slug && description == other.description && functionType == other.functionType && promptData == other.promptData && tags == other.tags && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, projectId, slug, description, functionType, promptData, tags, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{name=$name, projectId=$projectId, slug=$slug, description=$description, functionType=$functionType, promptData=$promptData, tags=$tags, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [PromptCreateParams]. + * Returns an immutable instance of [PromptCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java @@ -546,265 +419,433 @@ private constructor( * .projectId() * .slug() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): PromptCreateParams = + PromptCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [PromptCreateParams]. */ - @NoAutoDetect - class Builder internal constructor() { + fun _body(): Body = body - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + override fun _headers(): Headers = additionalHeaders - @JvmSynthetic - internal fun from(promptCreateParams: PromptCreateParams) = apply { - body = promptCreateParams.body.toBuilder() - additionalHeaders = promptCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = promptCreateParams.additionalQueryParams.toBuilder() - } + override fun _queryParams(): QueryParams = additionalQueryParams - /** Name of the prompt */ - fun name(name: String) = apply { body.name(name) } + class Body + private constructor( + private val name: JsonField, + private val projectId: JsonField, + private val slug: JsonField, + private val description: JsonField, + private val functionType: JsonField, + private val promptData: JsonField, + private val tags: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") + @ExcludeMissing + projectId: JsonField = JsonMissing.of(), + @JsonProperty("slug") @ExcludeMissing slug: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("function_type") + @ExcludeMissing + functionType: JsonField = JsonMissing.of(), + @JsonProperty("prompt_data") + @ExcludeMissing + promptData: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this(name, projectId, slug, description, functionType, promptData, tags, mutableMapOf()) /** - * Sets [Builder.name] to an arbitrary JSON value. + * Name of the prompt * - * 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. + * @throws BraintrustInvalidDataException 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(name: JsonField) = apply { body.name(name) } - - /** Unique identifier for the project that the prompt belongs under */ - fun projectId(projectId: String) = apply { body.projectId(projectId) } + fun name(): String = name.getRequired("name") /** - * Sets [Builder.projectId] to an arbitrary JSON value. + * Unique identifier for the project that the prompt belongs under * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException 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 projectId(projectId: JsonField) = apply { body.projectId(projectId) } - - /** Unique identifier for the prompt */ - fun slug(slug: String) = apply { body.slug(slug) } + fun projectId(): String = projectId.getRequired("project_id") /** - * Sets [Builder.slug] to an arbitrary JSON value. + * Unique identifier for the prompt * - * You should usually call [Builder.slug] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException 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 slug(slug: JsonField) = apply { body.slug(slug) } - - /** Textual description of the prompt */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + fun slug(): String = slug.getRequired("slug") /** - * Sets [Builder.description] to an arbitrary JSON value. + * Textual description of the prompt * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun description(description: JsonField) = apply { body.description(description) } + fun description(): Optional = description.getOptional("description") - fun functionType(functionType: FunctionType?) = apply { body.functionType(functionType) } + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun functionType(): Optional = functionType.getOptional("function_type") - /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ - fun functionType(functionType: Optional) = - functionType(functionType.getOrNull()) + /** + * The prompt, model, and its parameters + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun promptData(): Optional = promptData.getOptional("prompt_data") /** - * Sets [Builder.functionType] to an arbitrary JSON value. + * A list of tags for the prompt * - * You should usually call [Builder.functionType] with a well-typed [FunctionType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun functionType(functionType: JsonField) = apply { - body.functionType(functionType) - } + fun tags(): Optional> = tags.getOptional("tags") - /** The prompt, model, and its parameters */ - fun promptData(promptData: PromptData?) = apply { body.promptData(promptData) } + /** + * 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 - /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ - fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId /** - * Sets [Builder.promptData] to an arbitrary JSON value. + * Returns the raw JSON value of [slug]. * - * You should usually call [Builder.promptData] with a well-typed [PromptData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * Unlike [slug], this method doesn't throw if the JSON field has an unexpected type. */ - fun promptData(promptData: JsonField) = apply { body.promptData(promptData) } + @JsonProperty("slug") @ExcludeMissing fun _slug(): JsonField = slug - /** A list of tags for the prompt */ - fun tags(tags: List?) = apply { body.tags(tags) } + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description - /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ - fun tags(tags: Optional>) = tags(tags.getOrNull()) + /** + * Returns the raw JSON value of [functionType]. + * + * Unlike [functionType], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_type") + @ExcludeMissing + fun _functionType(): JsonField = functionType /** - * Sets [Builder.tags] to an arbitrary JSON value. + * Returns the raw JSON value of [promptData]. * - * You should usually call [Builder.tags] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. */ - fun tags(tags: JsonField>) = apply { body.tags(tags) } + @JsonProperty("prompt_data") + @ExcludeMissing + fun _promptData(): JsonField = promptData /** - * Adds a single [String] to [tags]. + * Returns the raw JSON value of [tags]. * - * @throws IllegalStateException if the field was previously set to a non-list. + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. */ - fun addTag(tag: String) = apply { body.addTag(tag) } + @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + + @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 + * .name() + * .projectId() + * .slug() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var projectId: JsonField? = null + private var slug: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var functionType: JsonField = JsonMissing.of() + private var promptData: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + projectId = body.projectId + slug = body.slug + description = body.description + functionType = body.functionType + promptData = body.promptData + tags = body.tags.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the prompt */ + 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 } + + /** Unique identifier for the project that the prompt belongs under */ + fun projectId(projectId: String) = projectId(JsonField.of(projectId)) + + /** + * Sets [Builder.projectId] to an arbitrary JSON value. + * + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun projectId(projectId: JsonField) = apply { this.projectId = projectId } + + /** Unique identifier for the prompt */ + fun slug(slug: String) = slug(JsonField.of(slug)) + + /** + * Sets [Builder.slug] to an arbitrary JSON value. + * + * You should usually call [Builder.slug] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun slug(slug: JsonField) = apply { this.slug = slug } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) - } + /** Textual description of the prompt */ + fun description(description: String?) = description(JsonField.ofNullable(description)) - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description } - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + fun functionType(functionType: FunctionType?) = + functionType(JsonField.ofNullable(functionType)) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ + fun functionType(functionType: Optional) = + functionType(functionType.getOrNull()) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Sets [Builder.functionType] to an arbitrary JSON value. + * + * You should usually call [Builder.functionType] with a well-typed [FunctionType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun functionType(functionType: JsonField) = apply { + this.functionType = functionType + } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** The prompt, model, and its parameters */ + fun promptData(promptData: PromptData?) = promptData(JsonField.ofNullable(promptData)) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ + fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * Sets [Builder.promptData] to an arbitrary JSON value. + * + * You should usually call [Builder.promptData] with a well-typed [PromptData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun promptData(promptData: JsonField) = apply { + this.promptData = promptData + } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** A list of tags for the prompt */ + fun tags(tags: List?) = tags(JsonField.ofNullable(tags)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.tags] to an arbitrary JSON value. + * + * You should usually call [Builder.tags] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tags(tags: JsonField>) = apply { + this.tags = tags.map { it.toMutableList() } + } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { + tags = + (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } + } - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * .slug() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("name", name), + checkRequired("projectId", projectId), + checkRequired("slug", slug), + description, + functionType, + promptData, + (tags ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + private var validated: Boolean = false - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun validate(): Body = apply { + if (validated) { + return@apply + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) + name() + projectId() + slug() + description() + functionType().ifPresent { it.validate() } + promptData().ifPresent { it.validate() } + tags() + validated = true } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (slug.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (functionType.asKnown().getOrNull()?.validity() ?: 0) + + (promptData.asKnown().getOrNull()?.validity() ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && slug == other.slug && description == other.description && functionType == other.functionType && promptData == other.promptData && tags == other.tags && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, projectId, slug, description, functionType, promptData, tags, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [PromptCreateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .slug() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): PromptCreateParams = - PromptCreateParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{name=$name, projectId=$projectId, slug=$slug, description=$description, functionType=$functionType, promptData=$promptData, tags=$tags, additionalProperties=$additionalProperties}" } class FunctionType @JsonCreator private constructor(private val value: JsonField) : @@ -909,6 +950,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): FunctionType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptData.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptData.kt index c47b3a79..9248eaac 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptData.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptData.kt @@ -9,11 +9,10 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect +import com.braintrustdata.api.core.allMaxBy import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -27,63 +26,64 @@ 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.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull /** The prompt, model, and its parameters */ -@NoAutoDetect class PromptData -@JsonCreator private constructor( - @JsonProperty("options") - @ExcludeMissing - private val options: JsonField = JsonMissing.of(), - @JsonProperty("origin") - @ExcludeMissing - private val origin: JsonField = JsonMissing.of(), - @JsonProperty("parser") - @ExcludeMissing - private val parser: JsonField = JsonMissing.of(), - @JsonProperty("prompt") - @ExcludeMissing - private val prompt: JsonField = JsonMissing.of(), - @JsonProperty("tool_functions") - @ExcludeMissing - private val toolFunctions: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val options: JsonField, + private val origin: JsonField, + private val parser: JsonField, + private val prompt: JsonField, + private val toolFunctions: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("options") + @ExcludeMissing + options: JsonField = JsonMissing.of(), + @JsonProperty("origin") @ExcludeMissing origin: JsonField = JsonMissing.of(), + @JsonProperty("parser") @ExcludeMissing parser: JsonField = JsonMissing.of(), + @JsonProperty("prompt") @ExcludeMissing prompt: JsonField = JsonMissing.of(), + @JsonProperty("tool_functions") + @ExcludeMissing + toolFunctions: JsonField> = JsonMissing.of(), + ) : this(options, origin, parser, prompt, toolFunctions, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun options(): Optional = Optional.ofNullable(options.getNullable("options")) + fun options(): Optional = options.getOptional("options") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun origin(): Optional = Optional.ofNullable(origin.getNullable("origin")) + fun origin(): Optional = origin.getOptional("origin") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun parser(): Optional = Optional.ofNullable(parser.getNullable("parser")) + fun parser(): Optional = parser.getOptional("parser") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun prompt(): Optional = Optional.ofNullable(prompt.getNullable("prompt")) + fun prompt(): Optional = prompt.getOptional("prompt") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun toolFunctions(): Optional> = - Optional.ofNullable(toolFunctions.getNullable("tool_functions")) + fun toolFunctions(): Optional> = toolFunctions.getOptional("tool_functions") /** * Returns the raw JSON value of [options]. @@ -122,24 +122,15 @@ private constructor( @ExcludeMissing fun _toolFunctions(): JsonField> = toolFunctions + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PromptData = apply { - if (validated) { - return@apply - } - - options().ifPresent { it.validate() } - origin().ifPresent { it.validate() } - parser().ifPresent { it.validate() } - prompt().ifPresent { it.validate() } - toolFunctions().ifPresent { it.forEach { it.validate() } } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -297,45 +288,84 @@ private constructor( parser, prompt, (toolFunctions ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): PromptData = apply { + if (validated) { + return@apply + } + + options().ifPresent { it.validate() } + origin().ifPresent { it.validate() } + parser().ifPresent { it.validate() } + prompt().ifPresent { it.validate() } + toolFunctions().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (options.asKnown().getOrNull()?.validity() ?: 0) + + (origin.asKnown().getOrNull()?.validity() ?: 0) + + (parser.asKnown().getOrNull()?.validity() ?: 0) + + (prompt.asKnown().getOrNull()?.validity() ?: 0) + + (toolFunctions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + class Origin - @JsonCreator private constructor( - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("prompt_id") - @ExcludeMissing - private val promptId: JsonField = JsonMissing.of(), - @JsonProperty("prompt_version") - @ExcludeMissing - private val promptVersion: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val projectId: JsonField, + private val promptId: JsonField, + private val promptVersion: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("project_id") + @ExcludeMissing + projectId: JsonField = JsonMissing.of(), + @JsonProperty("prompt_id") + @ExcludeMissing + promptId: JsonField = JsonMissing.of(), + @JsonProperty("prompt_version") + @ExcludeMissing + promptVersion: JsonField = JsonMissing.of(), + ) : this(projectId, promptId, promptVersion, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun projectId(): Optional = Optional.ofNullable(projectId.getNullable("project_id")) + fun projectId(): Optional = projectId.getOptional("project_id") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun promptId(): Optional = Optional.ofNullable(promptId.getNullable("prompt_id")) + fun promptId(): Optional = promptId.getOptional("prompt_id") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun promptVersion(): Optional = - Optional.ofNullable(promptVersion.getNullable("prompt_version")) + fun promptVersion(): Optional = promptVersion.getOptional("prompt_version") /** * Returns the raw JSON value of [projectId]. @@ -361,22 +391,15 @@ private constructor( @ExcludeMissing fun _promptVersion(): JsonField = promptVersion + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Origin = apply { - if (validated) { - return@apply - } - - projectId() - promptId() - promptVersion() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -462,9 +485,42 @@ private constructor( * Further updates to this [Builder] will not mutate the returned instance. */ fun build(): Origin = - Origin(projectId, promptId, promptVersion, additionalProperties.toImmutable()) + Origin(projectId, promptId, promptVersion, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Origin = apply { + if (validated) { + return@apply + } + + projectId() + promptId() + promptVersion() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (projectId.asKnown().isPresent) 1 else 0) + + (if (promptId.asKnown().isPresent) 1 else 0) + + (if (promptVersion.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -483,21 +539,23 @@ private constructor( "Origin{projectId=$projectId, promptId=$promptId, promptVersion=$promptVersion, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Parser - @JsonCreator private constructor( - @JsonProperty("choice_scores") - @ExcludeMissing - private val choiceScores: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonProperty("use_cot") - @ExcludeMissing - private val useCot: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val choiceScores: JsonField, + private val type: JsonField, + private val useCot: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("choice_scores") + @ExcludeMissing + choiceScores: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("use_cot") @ExcludeMissing useCot: JsonField = JsonMissing.of(), + ) : this(choiceScores, type, useCot, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected value). @@ -540,22 +598,15 @@ private constructor( */ @JsonProperty("use_cot") @ExcludeMissing fun _useCot(): JsonField = useCot + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Parser = apply { - if (validated) { - return@apply - } - - choiceScores().validate() - type() - useCot() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -663,32 +714,54 @@ private constructor( checkRequired("choiceScores", choiceScores), checkRequired("type", type), checkRequired("useCot", useCot), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Parser = apply { + if (validated) { + return@apply + } + + choiceScores().validate() + type().validate() + useCot() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (choiceScores.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + + (if (useCot.asKnown().isPresent) 1 else 0) + class ChoiceScores @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): ChoiceScores = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -737,6 +810,34 @@ private constructor( fun build(): ChoiceScores = ChoiceScores(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): ChoiceScores = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -835,6 +936,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -889,13 +1017,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { completion != null -> visitor.visitCompletion(completion) chat != null -> visitor.visitChat(chat) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -918,6 +1045,32 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitCompletion(completion: Completion) = completion.validity() + + override fun visitChat(chat: Chat) = chat.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -970,16 +1123,28 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Prompt { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Prompt(completion = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Prompt(chat = it, _json = json) - } - - return Prompt(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Prompt(completion = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Prompt(chat = 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 -> Prompt(_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() + } } } @@ -999,20 +1164,21 @@ private constructor( } } - @NoAutoDetect class Completion - @JsonCreator private constructor( - @JsonProperty("content") - @ExcludeMissing - private val content: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val content: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(content, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -1041,21 +1207,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Completion = apply { - if (validated) { - return@apply - } - - content() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1148,10 +1308,41 @@ private constructor( Completion( checkRequired("content", content), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Completion = apply { + if (validated) { + return@apply + } + + content() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (content.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1236,6 +1427,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -1267,23 +1485,23 @@ private constructor( "Completion{content=$content, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Chat - @JsonCreator private constructor( - @JsonProperty("messages") - @ExcludeMissing - private val messages: JsonField> = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonProperty("tools") - @ExcludeMissing - private val tools: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val messages: JsonField>, + private val type: JsonField, + private val tools: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("messages") + @ExcludeMissing + messages: JsonField> = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("tools") @ExcludeMissing tools: JsonField = JsonMissing.of(), + ) : this(messages, type, tools, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -1302,7 +1520,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun tools(): Optional = Optional.ofNullable(tools.getNullable("tools")) + fun tools(): Optional = tools.getOptional("tools") /** * Returns the raw JSON value of [messages]. @@ -1328,22 +1546,15 @@ private constructor( */ @JsonProperty("tools") @ExcludeMissing fun _tools(): JsonField = tools + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Chat = apply { - if (validated) { - return@apply - } - - messages().forEach { it.validate() } - type() - tools() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1485,10 +1696,43 @@ private constructor( checkRequired("messages", messages).map { it.toImmutable() }, checkRequired("type", type), tools, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Chat = apply { + if (validated) { + return@apply + } + + messages().forEach { it.validate() } + type().validate() + tools() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + + (type.asKnown().getOrNull()?.validity() ?: 0) + + (if (tools.asKnown().isPresent) 1 else 0) + @JsonDeserialize(using = Message.Deserializer::class) @JsonSerialize(using = Message.Serializer::class) class Message @@ -1540,8 +1784,8 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { system != null -> visitor.visitSystem(system) user != null -> visitor.visitUser(user) assistant != null -> visitor.visitAssistant(assistant) @@ -1550,7 +1794,6 @@ private constructor( fallback != null -> visitor.visitFallback(fallback) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1589,6 +1832,40 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitSystem(system: System) = system.validity() + + override fun visitUser(user: User) = user.validity() + + override fun visitAssistant(assistant: Assistant) = assistant.validity() + + override fun visitTool(tool: Tool) = tool.validity() + + override fun visitFunction(function: Function) = function.validity() + + override fun visitFallback(fallback: Fallback) = fallback.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1665,32 +1942,41 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Message { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Message(system = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Message(user = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Message(assistant = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Message(tool = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Message(function = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Message(fallback = it, _json = json) - } - - return Message(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Message(system = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Message(user = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Message(assistant = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Message(tool = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Message(function = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Message(fallback = 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() + } } } @@ -1714,23 +2000,27 @@ private constructor( } } - @NoAutoDetect class System - @JsonCreator private constructor( - @JsonProperty("role") - @ExcludeMissing - private val role: JsonField = JsonMissing.of(), - @JsonProperty("content") - @ExcludeMissing - private val content: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val role: JsonField, + private val content: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("role") + @ExcludeMissing + role: JsonField = JsonMissing.of(), + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + ) : this(role, content, name, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -1742,14 +2032,13 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ - fun content(): Optional = - Optional.ofNullable(content.getNullable("content")) + fun content(): Optional = content.getOptional("content") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun name(): Optional = name.getOptional("name") /** * Returns the raw JSON value of [role]. @@ -1777,22 +2066,15 @@ private constructor( */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): System = apply { - if (validated) { - return@apply - } - - role() - content() - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1898,10 +2180,43 @@ private constructor( checkRequired("role", role), content, name, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): System = apply { + if (validated) { + return@apply + } + + role().validate() + content() + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + + (if (content.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + class Role @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1990,6 +2305,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Role = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2021,23 +2364,27 @@ private constructor( "System{role=$role, content=$content, name=$name, additionalProperties=$additionalProperties}" } - @NoAutoDetect class User - @JsonCreator private constructor( - @JsonProperty("role") - @ExcludeMissing - private val role: JsonField = JsonMissing.of(), - @JsonProperty("content") - @ExcludeMissing - private val content: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val role: JsonField, + private val content: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("role") + @ExcludeMissing + role: JsonField = JsonMissing.of(), + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + ) : this(role, content, name, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -2049,14 +2396,13 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ - fun content(): Optional = - Optional.ofNullable(content.getNullable("content")) + fun content(): Optional = content.getOptional("content") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun name(): Optional = name.getOptional("name") /** * Returns the raw JSON value of [role]. @@ -2084,22 +2430,15 @@ private constructor( */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): User = apply { - if (validated) { - return@apply - } - - role() - content().ifPresent { it.validate() } - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2212,10 +2551,43 @@ private constructor( checkRequired("role", role), content, name, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): User = apply { + if (validated) { + return@apply + } + + role().validate() + content().ifPresent { it.validate() } + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + + (content.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + class Role @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -2304,6 +2676,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Role = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2341,13 +2741,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { text != null -> visitor.visitText(text) array != null -> visitor.visitArray(array) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -2370,6 +2769,34 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitText(text: String) = 1 + + override fun visitArray( + array: List + ) = array.sumOf { it.validity().toInt() } + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2427,20 +2854,35 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Content { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef())?.let { - return Content(text = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(text = it, _json = json) + }, + tryDeserialize( + node, + jacksonTypeRef< + List + >(), + ) + ?.let { Content(array = 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 object). + 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() } - tryDeserialize( - node, - jacksonTypeRef>(), - ) { - it.forEach { it.validate() } - } - ?.let { - return Content(array = it, _json = json) - } - - return Content(_json = json) } } @@ -2486,13 +2928,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { text != null -> visitor.visitText(text) image != null -> visitor.visitImage(image) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -2519,6 +2960,36 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitText( + text: ChatCompletionContentPartText + ) = text.validity() + + override fun visitImage( + image: ChatCompletionContentPartImage + ) = image.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2591,32 +3062,49 @@ private constructor( ): ChatCompletionContentPart { val json = JsonValue.fromJsonNode(node) - tryDeserialize( - node, - jacksonTypeRef(), - ) { - it.validate() - } - ?.let { - return ChatCompletionContentPart( - text = it, - _json = json, - ) - } - tryDeserialize( - node, - jacksonTypeRef(), - ) { - it.validate() - } - ?.let { - return ChatCompletionContentPart( - image = it, - _json = json, + val bestMatches = + sequenceOf( + tryDeserialize( + node, + jacksonTypeRef< + ChatCompletionContentPartText + >(), + ) + ?.let { + ChatCompletionContentPart( + text = it, + _json = json, + ) + }, + tryDeserialize( + node, + jacksonTypeRef< + ChatCompletionContentPartImage + >(), + ) + ?.let { + ChatCompletionContentPart( + image = it, + _json = json, + ) + }, ) - } - - return ChatCompletionContentPart(_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 -> ChatCompletionContentPart(_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() + } } } @@ -2662,30 +3150,35 @@ private constructor( "User{role=$role, content=$content, name=$name, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Assistant - @JsonCreator private constructor( - @JsonProperty("role") - @ExcludeMissing - private val role: JsonField = JsonMissing.of(), - @JsonProperty("content") - @ExcludeMissing - private val content: JsonField = JsonMissing.of(), - @JsonProperty("function_call") - @ExcludeMissing - private val functionCall: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("tool_calls") - @ExcludeMissing - private val toolCalls: JsonField> = - JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val role: JsonField, + private val content: JsonField, + private val functionCall: JsonField, + private val name: JsonField, + private val toolCalls: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("role") + @ExcludeMissing + role: 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("tool_calls") + @ExcludeMissing + toolCalls: JsonField> = JsonMissing.of(), + ) : this(role, content, functionCall, name, toolCalls, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -2697,28 +3190,27 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ - fun content(): Optional = - Optional.ofNullable(content.getNullable("content")) + fun content(): Optional = content.getOptional("content") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ fun functionCall(): Optional = - Optional.ofNullable(functionCall.getNullable("function_call")) + functionCall.getOptional("function_call") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun name(): Optional = name.getOptional("name") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ fun toolCalls(): Optional> = - Optional.ofNullable(toolCalls.getNullable("tool_calls")) + toolCalls.getOptional("tool_calls") /** * Returns the raw JSON value of [role]. @@ -2766,24 +3258,15 @@ private constructor( @ExcludeMissing fun _toolCalls(): JsonField> = toolCalls + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Assistant = apply { - if (validated) { - return@apply - } - - role() - content() - functionCall().ifPresent { it.validate() } - name() - toolCalls().ifPresent { it.forEach { it.validate() } } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2957,10 +3440,47 @@ private constructor( functionCall, name, (toolCalls ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Assistant = apply { + if (validated) { + return@apply + } + + role().validate() + content() + functionCall().ifPresent { it.validate() } + name() + toolCalls().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + + (if (content.asKnown().isPresent) 1 else 0) + + (functionCall.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (toolCalls.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + class Role @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -3049,6 +3569,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Role = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -3062,21 +3610,23 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class FunctionCall - @JsonCreator private constructor( - @JsonProperty("arguments") - @ExcludeMissing - private val arguments: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val arguments: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("arguments") + @ExcludeMissing + arguments: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + ) : this(arguments, name, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an * unexpected type or is unexpectedly missing or null (e.g. if the server @@ -3109,21 +3659,15 @@ private constructor( */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): FunctionCall = apply { - if (validated) { - return@apply - } - - arguments() - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3222,10 +3766,41 @@ private constructor( FunctionCall( checkRequired("arguments", arguments), checkRequired("name", name), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): FunctionCall = apply { + if (validated) { + return@apply + } + + arguments() + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3262,23 +3837,27 @@ private constructor( "Assistant{role=$role, content=$content, functionCall=$functionCall, name=$name, toolCalls=$toolCalls, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Tool - @JsonCreator private constructor( - @JsonProperty("role") - @ExcludeMissing - private val role: JsonField = JsonMissing.of(), - @JsonProperty("content") - @ExcludeMissing - private val content: JsonField = JsonMissing.of(), - @JsonProperty("tool_call_id") - @ExcludeMissing - private val toolCallId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val role: JsonField, + private val content: JsonField, + private val toolCallId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("role") + @ExcludeMissing + role: JsonField = JsonMissing.of(), + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("tool_call_id") + @ExcludeMissing + toolCallId: JsonField = JsonMissing.of(), + ) : this(role, content, toolCallId, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -3290,15 +3869,13 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ - fun content(): Optional = - Optional.ofNullable(content.getNullable("content")) + fun content(): Optional = content.getOptional("content") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ - fun toolCallId(): Optional = - Optional.ofNullable(toolCallId.getNullable("tool_call_id")) + fun toolCallId(): Optional = toolCallId.getOptional("tool_call_id") /** * Returns the raw JSON value of [role]. @@ -3328,22 +3905,15 @@ private constructor( @ExcludeMissing fun _toolCallId(): JsonField = toolCallId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Tool = apply { - if (validated) { - return@apply - } - - role() - content() - toolCallId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3451,10 +4021,43 @@ private constructor( checkRequired("role", role), content, toolCallId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Tool = apply { + if (validated) { + return@apply + } + + role().validate() + content() + toolCallId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + + (if (content.asKnown().isPresent) 1 else 0) + + (if (toolCallId.asKnown().isPresent) 1 else 0) + class Role @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -3543,6 +4146,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Role = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -3574,23 +4205,27 @@ private constructor( "Tool{role=$role, content=$content, toolCallId=$toolCallId, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Function - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("role") - @ExcludeMissing - private val role: JsonField = JsonMissing.of(), - @JsonProperty("content") - @ExcludeMissing - private val content: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private constructor( + private val name: JsonField, + private val role: JsonField, + private val content: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("role") + @ExcludeMissing + role: JsonField = JsonMissing.of(), + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + ) : this(name, role, content, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -3609,8 +4244,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ - fun content(): Optional = - Optional.ofNullable(content.getNullable("content")) + fun content(): Optional = content.getOptional("content") /** * Returns the raw JSON value of [name]. @@ -3638,22 +4272,15 @@ private constructor( @ExcludeMissing fun _content(): JsonField = content + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Function = apply { - if (validated) { - return@apply - } - - name() - role() - content() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3761,10 +4388,43 @@ private constructor( checkRequired("name", name), checkRequired("role", role), content, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Function = apply { + if (validated) { + return@apply + } + + name() + role().validate() + content() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (role.asKnown().getOrNull()?.validity() ?: 0) + + (if (content.asKnown().isPresent) 1 else 0) + class Role @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -3853,6 +4513,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Role = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -3884,20 +4572,23 @@ private constructor( "Function{name=$name, role=$role, content=$content, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Fallback - @JsonCreator private constructor( - @JsonProperty("role") - @ExcludeMissing - private val role: JsonField = JsonMissing.of(), - @JsonProperty("content") - @ExcludeMissing - private val content: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val role: JsonField, + private val content: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("role") + @ExcludeMissing + role: JsonField = JsonMissing.of(), + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + ) : this(role, content, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -3909,8 +4600,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type (e.g. if the server responded with an unexpected value). */ - fun content(): Optional = - Optional.ofNullable(content.getNullable("content")) + fun content(): Optional = content.getOptional("content") /** * Returns the raw JSON value of [role]. @@ -3930,21 +4620,15 @@ private constructor( @ExcludeMissing fun _content(): JsonField = content + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Fallback = apply { - if (validated) { - return@apply - } - - role() - content() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -4039,10 +4723,41 @@ private constructor( Fallback( checkRequired("role", role), content, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Fallback = apply { + if (validated) { + return@apply + } + + role().validate() + content() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + + (if (content.asKnown().isPresent) 1 else 0) + class Role @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -4131,6 +4846,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Role = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -4247,6 +4990,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -4302,13 +5072,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { function != null -> visitor.visitFunction(function) global != null -> visitor.visitGlobal(global) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -4331,6 +5100,32 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitFunction(function: Function) = function.validity() + + override fun visitGlobal(global: Global) = global.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -4386,16 +5181,28 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): ToolFunction { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return ToolFunction(function = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return ToolFunction(global = it, _json = json) - } - - return ToolFunction(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + ToolFunction(function = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + ToolFunction(global = 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 -> ToolFunction(_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() + } } } @@ -4415,20 +5222,19 @@ private constructor( } } - @NoAutoDetect class Function - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(id, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -4457,21 +5263,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Function = apply { - if (validated) { - return@apply - } - - id() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -4564,10 +5364,41 @@ private constructor( Function( checkRequired("id", id), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Function = apply { + if (validated) { + return@apply + } + + id() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -4652,6 +5483,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -4683,20 +5541,19 @@ private constructor( "Function{id=$id, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Global - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(name, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -4725,21 +5582,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Global = apply { - if (validated) { - return@apply - } - - name() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -4832,10 +5683,41 @@ private constructor( Global( checkRequired("name", name), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Global = apply { + if (validated) { + return@apply + } + + name() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -4920,6 +5802,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptDeleteParams.kt index 548ac609..e5a58880 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptDeleteParams.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,26 +23,11 @@ private constructor( /** Prompt id */ fun promptId(): String = promptId - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> promptId - else -> "" - } - } + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -61,7 +45,6 @@ private constructor( } /** A builder for [PromptDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var promptId: String? = null @@ -221,6 +204,19 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> promptId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListPage.kt index 54e69368..abba5831 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListPage.kt @@ -2,161 +2,115 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.PromptService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all prompts. The prompts are sorted by creation date, with the most recently-created - * prompts coming first - */ +/** @see [PromptService.list] */ class PromptListPage private constructor( - private val promptsService: PromptService, + private val service: PromptService, private val params: PromptListParams, - private val response: Response, + private val response: PromptListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [PromptListPageResponse], but gracefully handles missing data. + * + * @see [PromptListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is PromptListPage && promptsService == other.promptsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(promptsService, params, response) /* spotless:on */ - - override fun toString() = - "PromptListPage{promptsService=$promptsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - PromptListParams.builder().from(params).endingBefore(objects().first().id()).build() - ) - } else { - Optional.of( - PromptListParams.builder().from(params).startingAfter(objects().last().id()).build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { promptsService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(promptsService: PromptService, params: PromptListParams, response: Response) = - PromptListPage(promptsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): PromptListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): PromptListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [PromptListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [PromptListPage]. */ + class Builder internal constructor() { - companion object { + private var service: PromptService? = null + private var params: PromptListParams? = null + private var response: PromptListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [PromptListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(promptListPage: PromptListPage) = apply { + service = promptListPage.service + params = promptListPage.params + response = promptListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: PromptService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: PromptListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: PromptListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [PromptListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): PromptListPage = + PromptListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: PromptListPage) : Iterable { @@ -177,4 +131,16 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is PromptListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = "PromptListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListPageAsync.kt index d360b8a7..e87031b9 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListPageAsync.kt @@ -2,163 +2,119 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.PromptServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all prompts. The prompts are sorted by creation date, with the most recently-created - * prompts coming first - */ +/** @see [PromptServiceAsync.list] */ class PromptListPageAsync private constructor( - private val promptsService: PromptServiceAsync, + private val service: PromptServiceAsync, private val params: PromptListParams, - private val response: Response, + private val response: PromptListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [PromptListPageResponse], but gracefully handles missing data. + * + * @see [PromptListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is PromptListPageAsync && promptsService == other.promptsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(promptsService, params, response) /* spotless:on */ - - override fun toString() = - "PromptListPageAsync{promptsService=$promptsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - PromptListParams.builder().from(params).endingBefore(objects().first().id()).build() - ) - } else { - Optional.of( - PromptListParams.builder().from(params).startingAfter(objects().last().id()).build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { promptsService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(promptsService: PromptServiceAsync, params: PromptListParams, response: Response) = - PromptListPageAsync(promptsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): PromptListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): PromptListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [PromptListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [PromptListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: PromptServiceAsync? = null + private var params: PromptListParams? = null + private var response: PromptListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [PromptListPageAsync]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(promptListPageAsync: PromptListPageAsync) = apply { + service = promptListPageAsync.service + params = promptListPageAsync.params + response = promptListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: PromptServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: PromptListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: PromptListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [PromptListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): PromptListPageAsync = + PromptListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: PromptListPageAsync) { @@ -186,4 +142,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is PromptListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "PromptListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListPageResponse.kt new file mode 100644 index 00000000..5af60fcc --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListPageResponse.kt @@ -0,0 +1,192 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class PromptListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") @ExcludeMissing objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of prompt objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [PromptListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PromptListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(promptListPageResponse: PromptListPageResponse) = apply { + objects = promptListPageResponse.objects.map { it.toMutableList() } + additionalProperties = promptListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of prompt objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [Prompt] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: Prompt) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [PromptListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): PromptListPageResponse = + PromptListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): PromptListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is PromptListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "PromptListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListParams.kt index d5c704fa..a5c5adda 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListParams.kt @@ -2,22 +2,10 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -96,35 +84,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - endingBefore?.let { put("ending_before", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - orgName?.let { put("org_name", it) } - projectId?.let { put("project_id", it) } - projectName?.let { put("project_name", it) } - promptName?.let { put("prompt_name", it) } - slug?.let { put("slug", it) } - startingAfter?.let { put("starting_after", it) } - version?.let { put("version", it) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -136,7 +95,6 @@ private constructor( } /** A builder for [PromptListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var endingBefore: String? = null @@ -382,17 +340,43 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + endingBefore?.let { put("ending_before", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + orgName?.let { put("org_name", it) } + projectId?.let { put("project_id", it) } + projectName?.let { put("project_name", it) } + promptName?.let { put("prompt_name", it) } + slug?.let { put("slug", it) } + startingAfter?.let { put("starting_after", it) } + version?.let { put("version", it) } + putAll(additionalQueryParams) + } + .build() + /** * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -407,15 +391,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -431,7 +412,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -448,51 +428,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptOptions.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptOptions.kt index c13395bf..92357d35 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptOptions.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptOptions.kt @@ -9,11 +9,10 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect +import com.braintrustdata.api.core.allMaxBy import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -27,41 +26,43 @@ 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.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class PromptOptions -@JsonCreator private constructor( - @JsonProperty("model") @ExcludeMissing private val model: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("position") - @ExcludeMissing - private val position: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val model: JsonField, + private val params: JsonField, + private val position: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of(), + @JsonProperty("params") @ExcludeMissing params: JsonField = JsonMissing.of(), + @JsonProperty("position") @ExcludeMissing position: JsonField = JsonMissing.of(), + ) : this(model, params, position, mutableMapOf()) + /** * @throws BraintrustInvalidDataException 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 BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) + fun params(): Optional = params.getOptional("params") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun position(): Optional = Optional.ofNullable(position.getNullable("position")) + fun position(): Optional = position.getOptional("position") /** * Returns the raw JSON value of [model]. @@ -84,22 +85,15 @@ private constructor( */ @JsonProperty("position") @ExcludeMissing fun _position(): JsonField = position + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PromptOptions = apply { - if (validated) { - return@apply - } - - model() - params().ifPresent { it.validate() } - position() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -200,9 +194,41 @@ private constructor( * Further updates to this [Builder] will not mutate the returned instance. */ fun build(): PromptOptions = - PromptOptions(model, params, position, additionalProperties.toImmutable()) + PromptOptions(model, params, position, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): PromptOptions = apply { + if (validated) { + return@apply + } + + model() + params().ifPresent { it.validate() } + position() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (if (position.asKnown().isPresent) 1 else 0) + @JsonDeserialize(using = Params.Deserializer::class) @JsonSerialize(using = Params.Serializer::class) class Params @@ -247,8 +273,8 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { openaiModel != null -> visitor.visitOpenAIModel(openaiModel) anthropicModel != null -> visitor.visitAnthropicModel(anthropicModel) googleModel != null -> visitor.visitGoogleModel(googleModel) @@ -256,7 +282,6 @@ private constructor( jsCompletion != null -> visitor.visitJsCompletion(jsCompletion) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -291,6 +316,43 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitOpenAIModel(openaiModel: OpenAIModelParams) = + openaiModel.validity() + + override fun visitAnthropicModel(anthropicModel: AnthropicModelParams) = + anthropicModel.validity() + + override fun visitGoogleModel(googleModel: GoogleModelParams) = + googleModel.validity() + + override fun visitWindowAiModel(windowAiModel: WindowAiModelParams) = + windowAiModel.validity() + + override fun visitJsCompletion(jsCompletion: JsCompletionParams) = + jsCompletion.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -366,28 +428,37 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Params { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Params(openaiModel = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Params(anthropicModel = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Params(googleModel = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Params(windowAiModel = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Params(jsCompletion = it, _json = json) - } - - return Params(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Params(openaiModel = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Params(anthropicModel = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Params(googleModel = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Params(windowAiModel = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Params(jsCompletion = 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 -> Params(_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() + } } } @@ -410,64 +481,90 @@ private constructor( } } - @NoAutoDetect class OpenAIModelParams - @JsonCreator private constructor( - @JsonProperty("frequency_penalty") - @ExcludeMissing - private val frequencyPenalty: JsonField = JsonMissing.of(), - @JsonProperty("function_call") - @ExcludeMissing - private val functionCall: JsonField = JsonMissing.of(), - @JsonProperty("max_completion_tokens") - @ExcludeMissing - private val maxCompletionTokens: JsonField = JsonMissing.of(), - @JsonProperty("max_tokens") - @ExcludeMissing - private val maxTokens: JsonField = JsonMissing.of(), - @JsonProperty("n") @ExcludeMissing private val n: JsonField = JsonMissing.of(), - @JsonProperty("presence_penalty") - @ExcludeMissing - private val presencePenalty: JsonField = JsonMissing.of(), - @JsonProperty("reasoning_effort") - @ExcludeMissing - private val reasoningEffort: JsonField = JsonMissing.of(), - @JsonProperty("response_format") - @ExcludeMissing - private val responseFormat: JsonField = JsonMissing.of(), - @JsonProperty("stop") - @ExcludeMissing - private val stop: JsonField> = JsonMissing.of(), - @JsonProperty("temperature") - @ExcludeMissing - private val temperature: JsonField = JsonMissing.of(), - @JsonProperty("tool_choice") - @ExcludeMissing - private val toolChoice: JsonField = JsonMissing.of(), - @JsonProperty("top_p") - @ExcludeMissing - private val topP: JsonField = JsonMissing.of(), - @JsonProperty("use_cache") - @ExcludeMissing - private val useCache: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val frequencyPenalty: JsonField, + private val functionCall: JsonField, + private val maxCompletionTokens: JsonField, + private val maxTokens: JsonField, + private val n: JsonField, + private val presencePenalty: JsonField, + private val reasoningEffort: JsonField, + private val responseFormat: JsonField, + private val stop: JsonField>, + private val temperature: JsonField, + private val toolChoice: JsonField, + private val topP: JsonField, + private val useCache: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("frequency_penalty") + @ExcludeMissing + frequencyPenalty: JsonField = JsonMissing.of(), + @JsonProperty("function_call") + @ExcludeMissing + functionCall: JsonField = JsonMissing.of(), + @JsonProperty("max_completion_tokens") + @ExcludeMissing + maxCompletionTokens: JsonField = JsonMissing.of(), + @JsonProperty("max_tokens") + @ExcludeMissing + maxTokens: JsonField = JsonMissing.of(), + @JsonProperty("n") @ExcludeMissing n: JsonField = JsonMissing.of(), + @JsonProperty("presence_penalty") + @ExcludeMissing + presencePenalty: JsonField = JsonMissing.of(), + @JsonProperty("reasoning_effort") + @ExcludeMissing + reasoningEffort: JsonField = JsonMissing.of(), + @JsonProperty("response_format") + @ExcludeMissing + responseFormat: JsonField = JsonMissing.of(), + @JsonProperty("stop") + @ExcludeMissing + stop: JsonField> = JsonMissing.of(), + @JsonProperty("temperature") + @ExcludeMissing + temperature: JsonField = JsonMissing.of(), + @JsonProperty("tool_choice") + @ExcludeMissing + toolChoice: JsonField = JsonMissing.of(), + @JsonProperty("top_p") @ExcludeMissing topP: JsonField = JsonMissing.of(), + @JsonProperty("use_cache") + @ExcludeMissing + useCache: JsonField = JsonMissing.of(), + ) : this( + frequencyPenalty, + functionCall, + maxCompletionTokens, + maxTokens, + n, + presencePenalty, + reasoningEffort, + responseFormat, + stop, + temperature, + toolChoice, + topP, + useCache, + mutableMapOf(), + ) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ fun frequencyPenalty(): Optional = - Optional.ofNullable(frequencyPenalty.getNullable("frequency_penalty")) + frequencyPenalty.getOptional("frequency_penalty") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun functionCall(): Optional = - Optional.ofNullable(functionCall.getNullable("function_call")) + fun functionCall(): Optional = functionCall.getOptional("function_call") /** * The successor to max_tokens @@ -476,74 +573,70 @@ private constructor( * if the server responded with an unexpected value). */ fun maxCompletionTokens(): Optional = - Optional.ofNullable(maxCompletionTokens.getNullable("max_completion_tokens")) + maxCompletionTokens.getOptional("max_completion_tokens") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun maxTokens(): Optional = - Optional.ofNullable(maxTokens.getNullable("max_tokens")) + fun maxTokens(): Optional = maxTokens.getOptional("max_tokens") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun n(): Optional = Optional.ofNullable(n.getNullable("n")) + fun n(): Optional = n.getOptional("n") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ fun presencePenalty(): Optional = - Optional.ofNullable(presencePenalty.getNullable("presence_penalty")) + presencePenalty.getOptional("presence_penalty") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ fun reasoningEffort(): Optional = - Optional.ofNullable(reasoningEffort.getNullable("reasoning_effort")) + reasoningEffort.getOptional("reasoning_effort") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ fun responseFormat(): Optional = - Optional.ofNullable(responseFormat.getNullable("response_format")) + responseFormat.getOptional("response_format") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun stop(): Optional> = Optional.ofNullable(stop.getNullable("stop")) + fun stop(): Optional> = stop.getOptional("stop") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun temperature(): Optional = - Optional.ofNullable(temperature.getNullable("temperature")) + fun temperature(): Optional = temperature.getOptional("temperature") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun toolChoice(): Optional = - Optional.ofNullable(toolChoice.getNullable("tool_choice")) + fun toolChoice(): Optional = toolChoice.getOptional("tool_choice") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun topP(): Optional = Optional.ofNullable(topP.getNullable("top_p")) + fun topP(): Optional = topP.getOptional("top_p") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun useCache(): Optional = - Optional.ofNullable(useCache.getNullable("use_cache")) + fun useCache(): Optional = useCache.getOptional("use_cache") /** * Returns the raw JSON value of [frequencyPenalty]. @@ -666,32 +759,15 @@ private constructor( @ExcludeMissing fun _useCache(): JsonField = useCache + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): OpenAIModelParams = apply { - if (validated) { - return@apply - } - - frequencyPenalty() - functionCall().ifPresent { it.validate() } - maxCompletionTokens() - maxTokens() - n() - presencePenalty() - reasoningEffort() - responseFormat().ifPresent { it.validate() } - stop() - temperature() - toolChoice().ifPresent { it.validate() } - topP() - useCache() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1006,10 +1082,63 @@ private constructor( toolChoice, topP, useCache, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): OpenAIModelParams = apply { + if (validated) { + return@apply + } + + frequencyPenalty() + functionCall().ifPresent { it.validate() } + maxCompletionTokens() + maxTokens() + n() + presencePenalty() + reasoningEffort().ifPresent { it.validate() } + responseFormat().ifPresent { it.validate() } + stop() + temperature() + toolChoice().ifPresent { it.validate() } + topP() + useCache() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (frequencyPenalty.asKnown().isPresent) 1 else 0) + + (functionCall.asKnown().getOrNull()?.validity() ?: 0) + + (if (maxCompletionTokens.asKnown().isPresent) 1 else 0) + + (if (maxTokens.asKnown().isPresent) 1 else 0) + + (if (n.asKnown().isPresent) 1 else 0) + + (if (presencePenalty.asKnown().isPresent) 1 else 0) + + (reasoningEffort.asKnown().getOrNull()?.validity() ?: 0) + + (responseFormat.asKnown().getOrNull()?.validity() ?: 0) + + (stop.asKnown().getOrNull()?.size ?: 0) + + (if (temperature.asKnown().isPresent) 1 else 0) + + (toolChoice.asKnown().getOrNull()?.validity() ?: 0) + + (if (topP.asKnown().isPresent) 1 else 0) + + (if (useCache.asKnown().isPresent) 1 else 0) + @JsonDeserialize(using = FunctionCall.Deserializer::class) @JsonSerialize(using = FunctionCall.Serializer::class) class FunctionCall @@ -1033,13 +1162,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { unionMember0 != null -> visitor.visitUnionMember0(unionMember0) function != null -> visitor.visitFunction(function) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1050,7 +1178,9 @@ private constructor( accept( object : Visitor { - override fun visitUnionMember0(unionMember0: UnionMember0) {} + override fun visitUnionMember0(unionMember0: UnionMember0) { + unionMember0.validate() + } override fun visitFunction(function: Function) { function.validate() @@ -1060,6 +1190,33 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitFunction(function: Function) = function.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1118,15 +1275,29 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): FunctionCall { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef())?.let { - return FunctionCall(unionMember0 = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionCall(unionMember0 = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionCall(function = 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 + // array). + 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() } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return FunctionCall(function = it, _json = json) - } - - return FunctionCall(_json = json) } } @@ -1242,6 +1413,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): UnionMember0 = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -1255,17 +1454,19 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class Function - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of() + ) : this(name, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -1281,20 +1482,15 @@ private constructor( */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Function = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1372,10 +1568,38 @@ private constructor( fun build(): Function = Function( checkRequired("name", name), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Function = apply { + if (validated) { + return@apply + } + + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1496,6 +1720,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ReasoningEffort = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -1539,14 +1790,13 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { jsonObject != null -> visitor.visitJsonObject(jsonObject) jsonSchema != null -> visitor.visitJsonSchema(jsonSchema) text != null -> visitor.visitText(text) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1573,6 +1823,36 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitJsonObject(jsonObject: JsonObject) = + jsonObject.validity() + + override fun visitJsonSchema(jsonSchema: JsonSchema) = + jsonSchema.validity() + + override fun visitText(text: Text) = text.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1638,20 +1918,32 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): ResponseFormat { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return ResponseFormat(jsonObject = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return ResponseFormat(jsonSchema = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return ResponseFormat(text = it, _json = json) - } - - return ResponseFormat(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + ResponseFormat(jsonObject = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + ResponseFormat(jsonSchema = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + ResponseFormat(text = 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 -> ResponseFormat(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } } } @@ -1672,20 +1964,22 @@ private constructor( } } - @NoAutoDetect class JsonObject - @JsonCreator private constructor( - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected - * type or is unexpectedly missing or null (e.g. if the server responded with + @JsonCreator + private constructor( + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * @throws BraintrustInvalidDataException 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 type(): Type = type.getRequired("type") @@ -1698,20 +1992,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): JsonObject = apply { - if (validated) { - return@apply - } - - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1789,10 +2078,38 @@ private constructor( fun build(): JsonObject = JsonObject( checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): JsonObject = apply { + if (validated) { + return@apply + } + + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1881,6 +2198,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -1912,20 +2257,23 @@ private constructor( "JsonObject{type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class JsonSchema - @JsonCreator private constructor( - @JsonProperty("json_schema") - @ExcludeMissing - private val jsonSchema: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val jsonSchema: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("json_schema") + @ExcludeMissing + jsonSchema: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(jsonSchema, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -1958,21 +2306,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): JsonSchema = apply { - if (validated) { - return@apply - } - - jsonSchema().validate() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2069,31 +2411,66 @@ private constructor( JsonSchema( checkRequired("jsonSchema", jsonSchema), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): JsonSchema = apply { + if (validated) { + return@apply + } + + jsonSchema().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (jsonSchema.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class InnerJsonSchema - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("schema") - @ExcludeMissing - private val schema: JsonField = JsonMissing.of(), - @JsonProperty("strict") - @ExcludeMissing - private val strict: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val name: JsonField, + private val description: JsonField, + private val schema: JsonField, + private val strict: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("schema") + @ExcludeMissing + schema: JsonField = JsonMissing.of(), + @JsonProperty("strict") + @ExcludeMissing + strict: JsonField = JsonMissing.of(), + ) : this(name, description, schema, strict, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an * unexpected type or is unexpectedly missing or null (e.g. if the server @@ -2106,24 +2483,21 @@ private constructor( * unexpected type (e.g. if the server responded with an unexpected * value). */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun description(): Optional = description.getOptional("description") /** * @throws BraintrustInvalidDataException if the JSON field has an * unexpected type (e.g. if the server responded with an unexpected * value). */ - fun schema(): Optional = - Optional.ofNullable(schema.getNullable("schema")) + fun schema(): Optional = schema.getOptional("schema") /** * @throws BraintrustInvalidDataException if the JSON field has an * unexpected type (e.g. if the server responded with an unexpected * value). */ - fun strict(): Optional = - Optional.ofNullable(strict.getNullable("strict")) + fun strict(): Optional = strict.getOptional("strict") /** * Returns the raw JSON value of [name]. @@ -2163,23 +2537,15 @@ private constructor( @ExcludeMissing fun _strict(): JsonField = strict + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): InnerJsonSchema = apply { - if (validated) { - return@apply - } - - name() - description() - schema().ifPresent { it.validate() } - strict() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2321,10 +2687,45 @@ private constructor( description, schema, strict, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): InnerJsonSchema = apply { + if (validated) { + return@apply + } + + name() + description() + schema().ifPresent { it.validate() } + strict() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (schema.asKnown().getOrNull()?.validity() ?: 0) + + (if (strict.asKnown().isPresent) 1 else 0) + @JsonDeserialize(using = Schema.Deserializer::class) @JsonSerialize(using = Schema.Serializer::class) class Schema @@ -2348,13 +2749,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { object_ != null -> visitor.visitObject(object_) string != null -> visitor.visitString(string) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -2375,6 +2775,33 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitObject(object_: Object) = + object_.validity() + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2431,15 +2858,29 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Schema { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Schema(object_ = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef())?.let { - return Schema(string = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { Schema(object_ = it, _json = json) }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { Schema(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 array). + 0 -> Schema(_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 Schema(_json = json) } } @@ -2460,13 +2901,11 @@ private constructor( } } - @NoAutoDetect class Object @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @@ -2474,16 +2913,6 @@ private constructor( fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Object = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -2543,6 +2972,36 @@ private constructor( fun build(): Object = Object(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Object = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2668,6 +3127,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2699,17 +3186,19 @@ private constructor( "JsonSchema{jsonSchema=$jsonSchema, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Text - @JsonCreator private constructor( - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of() + ) : this(type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -2725,20 +3214,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Text = apply { - if (validated) { - return@apply - } - - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -2814,9 +3298,37 @@ private constructor( * @throws IllegalStateException if any required field is unset. */ fun build(): Text = - Text(checkRequired("type", type), additionalProperties.toImmutable()) + Text(checkRequired("type", type), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Text = apply { + if (validated) { + return@apply + } + + type().validate() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -2905,6 +3417,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -2960,13 +3500,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { unionMember0 != null -> visitor.visitUnionMember0(unionMember0) function != null -> visitor.visitFunction(function) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -2977,7 +3516,9 @@ private constructor( accept( object : Visitor { - override fun visitUnionMember0(unionMember0: UnionMember0) {} + override fun visitUnionMember0(unionMember0: UnionMember0) { + unionMember0.validate() + } override fun visitFunction(function: Function) { function.validate() @@ -2987,6 +3528,33 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 visitFunction(function: Function) = function.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3044,15 +3612,29 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): ToolChoice { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef())?.let { - return ToolChoice(unionMember0 = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + ToolChoice(unionMember0 = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + ToolChoice(function = 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 + // array). + 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() } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return ToolChoice(function = it, _json = json) - } - - return ToolChoice(_json = json) } } @@ -3174,6 +3756,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): UnionMember0 = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -3187,20 +3797,23 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class Function - @JsonCreator private constructor( - @JsonProperty("function") - @ExcludeMissing - private val function: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val function: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("function") + @ExcludeMissing + function: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(function, type, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected * type or is unexpectedly missing or null (e.g. if the server responded with @@ -3233,21 +3846,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Function = apply { - if (validated) { - return@apply - } - - function().validate() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3343,22 +3950,54 @@ private constructor( Function( checkRequired("function", function), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Function = apply { + if (validated) { + return@apply + } + + function().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (function.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class InnerFunction - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val name: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of() + ) : this(name, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an * unexpected type or is unexpectedly missing or null (e.g. if the server @@ -3374,20 +4013,15 @@ private constructor( */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): InnerFunction = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3468,10 +4102,38 @@ private constructor( fun build(): InnerFunction = InnerFunction( checkRequired("name", name), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): InnerFunction = apply { + if (validated) { + return@apply + } + + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3578,6 +4240,34 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -3628,35 +4318,48 @@ private constructor( "OpenAIModelParams{frequencyPenalty=$frequencyPenalty, functionCall=$functionCall, maxCompletionTokens=$maxCompletionTokens, maxTokens=$maxTokens, n=$n, presencePenalty=$presencePenalty, reasoningEffort=$reasoningEffort, responseFormat=$responseFormat, stop=$stop, temperature=$temperature, toolChoice=$toolChoice, topP=$topP, useCache=$useCache, additionalProperties=$additionalProperties}" } - @NoAutoDetect class AnthropicModelParams - @JsonCreator private constructor( - @JsonProperty("max_tokens") - @ExcludeMissing - private val maxTokens: JsonField = JsonMissing.of(), - @JsonProperty("temperature") - @ExcludeMissing - private val temperature: JsonField = JsonMissing.of(), - @JsonProperty("max_tokens_to_sample") - @ExcludeMissing - private val maxTokensToSample: JsonField = JsonMissing.of(), - @JsonProperty("stop_sequences") - @ExcludeMissing - private val stopSequences: JsonField> = JsonMissing.of(), - @JsonProperty("top_k") - @ExcludeMissing - private val topK: JsonField = JsonMissing.of(), - @JsonProperty("top_p") - @ExcludeMissing - private val topP: JsonField = JsonMissing.of(), - @JsonProperty("use_cache") - @ExcludeMissing - private val useCache: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val maxTokens: JsonField, + private val temperature: JsonField, + private val maxTokensToSample: JsonField, + private val stopSequences: JsonField>, + private val topK: JsonField, + private val topP: JsonField, + private val useCache: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("max_tokens") + @ExcludeMissing + maxTokens: JsonField = JsonMissing.of(), + @JsonProperty("temperature") + @ExcludeMissing + temperature: JsonField = JsonMissing.of(), + @JsonProperty("max_tokens_to_sample") + @ExcludeMissing + maxTokensToSample: JsonField = JsonMissing.of(), + @JsonProperty("stop_sequences") + @ExcludeMissing + stopSequences: JsonField> = JsonMissing.of(), + @JsonProperty("top_k") @ExcludeMissing topK: JsonField = JsonMissing.of(), + @JsonProperty("top_p") @ExcludeMissing topP: JsonField = JsonMissing.of(), + @JsonProperty("use_cache") + @ExcludeMissing + useCache: JsonField = JsonMissing.of(), + ) : this( + maxTokens, + temperature, + maxTokensToSample, + stopSequences, + topK, + topP, + useCache, + mutableMapOf(), + ) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected @@ -3678,33 +4381,32 @@ private constructor( * if the server responded with an unexpected value). */ fun maxTokensToSample(): Optional = - Optional.ofNullable(maxTokensToSample.getNullable("max_tokens_to_sample")) + maxTokensToSample.getOptional("max_tokens_to_sample") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ fun stopSequences(): Optional> = - Optional.ofNullable(stopSequences.getNullable("stop_sequences")) + stopSequences.getOptional("stop_sequences") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun topK(): Optional = Optional.ofNullable(topK.getNullable("top_k")) + fun topK(): Optional = topK.getOptional("top_k") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun topP(): Optional = Optional.ofNullable(topP.getNullable("top_p")) + fun topP(): Optional = topP.getOptional("top_p") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun useCache(): Optional = - Optional.ofNullable(useCache.getNullable("use_cache")) + fun useCache(): Optional = useCache.getOptional("use_cache") /** * Returns the raw JSON value of [maxTokens]. @@ -3770,26 +4472,15 @@ private constructor( @ExcludeMissing fun _useCache(): JsonField = useCache + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AnthropicModelParams = apply { - if (validated) { - return@apply - } - - maxTokens() - temperature() - maxTokensToSample() - stopSequences() - topK() - topP() - useCache() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -3973,10 +4664,51 @@ private constructor( topK, topP, useCache, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): AnthropicModelParams = apply { + if (validated) { + return@apply + } + + maxTokens() + temperature() + maxTokensToSample() + stopSequences() + topK() + topP() + useCache() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (maxTokens.asKnown().isPresent) 1 else 0) + + (if (temperature.asKnown().isPresent) 1 else 0) + + (if (maxTokensToSample.asKnown().isPresent) 1 else 0) + + (stopSequences.asKnown().getOrNull()?.size ?: 0) + + (if (topK.asKnown().isPresent) 1 else 0) + + (if (topP.asKnown().isPresent) 1 else 0) + + (if (useCache.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3995,61 +4727,60 @@ private constructor( "AnthropicModelParams{maxTokens=$maxTokens, temperature=$temperature, maxTokensToSample=$maxTokensToSample, stopSequences=$stopSequences, topK=$topK, topP=$topP, useCache=$useCache, additionalProperties=$additionalProperties}" } - @NoAutoDetect class GoogleModelParams - @JsonCreator private constructor( - @JsonProperty("maxOutputTokens") - @ExcludeMissing - private val maxOutputTokens: JsonField = JsonMissing.of(), - @JsonProperty("temperature") - @ExcludeMissing - private val temperature: JsonField = JsonMissing.of(), - @JsonProperty("topK") - @ExcludeMissing - private val topK: JsonField = JsonMissing.of(), - @JsonProperty("topP") - @ExcludeMissing - private val topP: JsonField = JsonMissing.of(), - @JsonProperty("use_cache") - @ExcludeMissing - private val useCache: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val maxOutputTokens: JsonField, + private val temperature: JsonField, + private val topK: JsonField, + private val topP: JsonField, + private val useCache: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("maxOutputTokens") + @ExcludeMissing + maxOutputTokens: JsonField = JsonMissing.of(), + @JsonProperty("temperature") + @ExcludeMissing + temperature: JsonField = JsonMissing.of(), + @JsonProperty("topK") @ExcludeMissing topK: JsonField = JsonMissing.of(), + @JsonProperty("topP") @ExcludeMissing topP: JsonField = JsonMissing.of(), + @JsonProperty("use_cache") + @ExcludeMissing + useCache: JsonField = JsonMissing.of(), + ) : this(maxOutputTokens, temperature, topK, topP, useCache, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun maxOutputTokens(): Optional = - Optional.ofNullable(maxOutputTokens.getNullable("maxOutputTokens")) + fun maxOutputTokens(): Optional = maxOutputTokens.getOptional("maxOutputTokens") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun temperature(): Optional = - Optional.ofNullable(temperature.getNullable("temperature")) + fun temperature(): Optional = temperature.getOptional("temperature") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun topK(): Optional = Optional.ofNullable(topK.getNullable("topK")) + fun topK(): Optional = topK.getOptional("topK") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun topP(): Optional = Optional.ofNullable(topP.getNullable("topP")) + fun topP(): Optional = topP.getOptional("topP") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun useCache(): Optional = - Optional.ofNullable(useCache.getNullable("use_cache")) + fun useCache(): Optional = useCache.getOptional("use_cache") /** * Returns the raw JSON value of [maxOutputTokens]. @@ -4095,24 +4826,15 @@ private constructor( @ExcludeMissing fun _useCache(): JsonField = useCache + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): GoogleModelParams = apply { - if (validated) { - return@apply - } - - maxOutputTokens() - temperature() - topK() - topP() - useCache() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -4238,10 +4960,47 @@ private constructor( topK, topP, useCache, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): GoogleModelParams = apply { + if (validated) { + return@apply + } + + maxOutputTokens() + temperature() + topK() + topP() + useCache() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (maxOutputTokens.asKnown().isPresent) 1 else 0) + + (if (temperature.asKnown().isPresent) 1 else 0) + + (if (topK.asKnown().isPresent) 1 else 0) + + (if (topP.asKnown().isPresent) 1 else 0) + + (if (useCache.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -4260,42 +5019,42 @@ private constructor( "GoogleModelParams{maxOutputTokens=$maxOutputTokens, temperature=$temperature, topK=$topK, topP=$topP, useCache=$useCache, additionalProperties=$additionalProperties}" } - @NoAutoDetect class WindowAiModelParams - @JsonCreator private constructor( - @JsonProperty("temperature") - @ExcludeMissing - private val temperature: JsonField = JsonMissing.of(), - @JsonProperty("topK") - @ExcludeMissing - private val topK: JsonField = JsonMissing.of(), - @JsonProperty("use_cache") - @ExcludeMissing - private val useCache: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val temperature: JsonField, + private val topK: JsonField, + private val useCache: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("temperature") + @ExcludeMissing + temperature: JsonField = JsonMissing.of(), + @JsonProperty("topK") @ExcludeMissing topK: JsonField = JsonMissing.of(), + @JsonProperty("use_cache") + @ExcludeMissing + useCache: JsonField = JsonMissing.of(), + ) : this(temperature, topK, useCache, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun temperature(): Optional = - Optional.ofNullable(temperature.getNullable("temperature")) + fun temperature(): Optional = temperature.getOptional("temperature") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun topK(): Optional = Optional.ofNullable(topK.getNullable("topK")) + fun topK(): Optional = topK.getOptional("topK") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun useCache(): Optional = - Optional.ofNullable(useCache.getNullable("use_cache")) + fun useCache(): Optional = useCache.getOptional("use_cache") /** * Returns the raw JSON value of [temperature]. @@ -4324,22 +5083,15 @@ private constructor( @ExcludeMissing fun _useCache(): JsonField = useCache + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): WindowAiModelParams = apply { - if (validated) { - return@apply - } - - temperature() - topK() - useCache() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -4434,10 +5186,43 @@ private constructor( temperature, topK, useCache, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): WindowAiModelParams = apply { + if (validated) { + return@apply + } + + temperature() + topK() + useCache() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (temperature.asKnown().isPresent) 1 else 0) + + (if (topK.asKnown().isPresent) 1 else 0) + + (if (useCache.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -4456,23 +5241,24 @@ private constructor( "WindowAiModelParams{temperature=$temperature, topK=$topK, useCache=$useCache, additionalProperties=$additionalProperties}" } - @NoAutoDetect class JsCompletionParams - @JsonCreator private constructor( - @JsonProperty("use_cache") - @ExcludeMissing - private val useCache: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val useCache: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("use_cache") + @ExcludeMissing + useCache: JsonField = JsonMissing.of() + ) : this(useCache, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ - fun useCache(): Optional = - Optional.ofNullable(useCache.getNullable("use_cache")) + fun useCache(): Optional = useCache.getOptional("use_cache") /** * Returns the raw JSON value of [useCache]. @@ -4484,20 +5270,15 @@ private constructor( @ExcludeMissing fun _useCache(): JsonField = useCache + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): JsCompletionParams = apply { - if (validated) { - return@apply - } - - useCache() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -4560,9 +5341,37 @@ private constructor( * Further updates to this [Builder] will not mutate the returned instance. */ fun build(): JsCompletionParams = - JsCompletionParams(useCache, additionalProperties.toImmutable()) + JsCompletionParams(useCache, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): JsCompletionParams = apply { + if (validated) { + return@apply + } + + useCache() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (useCache.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptReplaceParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptReplaceParams.kt index 7521b155..3274f771 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptReplaceParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptReplaceParams.kt @@ -7,19 +7,18 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -144,401 +143,275 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun toBuilder() = Builder().from(this) - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("slug") - @ExcludeMissing - private val slug: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("function_type") - @ExcludeMissing - private val functionType: JsonField = JsonMissing.of(), - @JsonProperty("prompt_data") - @ExcludeMissing - private val promptData: JsonField = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + companion object { /** - * Name of the prompt + * Returns a mutable builder for constructing an instance of [PromptReplaceParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .name() + * .projectId() + * .slug() + * ``` */ - fun name(): String = name.getRequired("name") + @JvmStatic fun builder() = Builder() + } - /** - * Unique identifier for the project that the prompt belongs under - * - * @throws BraintrustInvalidDataException 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 projectId(): String = projectId.getRequired("project_id") + /** A builder for [PromptReplaceParams]. */ + class Builder internal constructor() { - /** - * Unique identifier for the prompt - * - * @throws BraintrustInvalidDataException 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 slug(): String = slug.getRequired("slug") + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - /** - * Textual description of the prompt - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + @JvmSynthetic + internal fun from(promptReplaceParams: PromptReplaceParams) = apply { + body = promptReplaceParams.body.toBuilder() + additionalHeaders = promptReplaceParams.additionalHeaders.toBuilder() + additionalQueryParams = promptReplaceParams.additionalQueryParams.toBuilder() + } /** - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [name] + * - [projectId] + * - [slug] + * - [description] + * - [functionType] + * - etc. */ - fun functionType(): Optional = - Optional.ofNullable(functionType.getNullable("function_type")) + fun body(body: Body) = apply { this.body = body.toBuilder() } - /** - * The prompt, model, and its parameters - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun promptData(): Optional = - Optional.ofNullable(promptData.getNullable("prompt_data")) + /** Name of the prompt */ + fun name(name: String) = apply { body.name(name) } /** - * A list of tags for the prompt + * Sets [Builder.name] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected 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 tags(): Optional> = Optional.ofNullable(tags.getNullable("tags")) + fun name(name: JsonField) = apply { body.name(name) } + + /** Unique identifier for the project that the prompt belongs under */ + fun projectId(projectId: String) = apply { body.projectId(projectId) } /** - * Returns the raw JSON value of [name]. + * Sets [Builder.projectId] to an arbitrary JSON value. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } + + /** Unique identifier for the prompt */ + fun slug(slug: String) = apply { body.slug(slug) } /** - * Returns the raw JSON value of [projectId]. + * Sets [Builder.slug] to an arbitrary JSON value. * - * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.slug] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId + fun slug(slug: JsonField) = apply { body.slug(slug) } + + /** Textual description of the prompt */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) /** - * Returns the raw JSON value of [slug]. + * Sets [Builder.description] to an arbitrary JSON value. * - * Unlike [slug], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("slug") @ExcludeMissing fun _slug(): JsonField = slug + fun description(description: JsonField) = apply { body.description(description) } + + fun functionType(functionType: FunctionType?) = apply { body.functionType(functionType) } + + /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ + fun functionType(functionType: Optional) = + functionType(functionType.getOrNull()) /** - * Returns the raw JSON value of [description]. + * Sets [Builder.functionType] to an arbitrary JSON value. * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.functionType] with a well-typed [FunctionType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description + fun functionType(functionType: JsonField) = apply { + body.functionType(functionType) + } + + /** The prompt, model, and its parameters */ + fun promptData(promptData: PromptData?) = apply { body.promptData(promptData) } + + /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ + fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) /** - * Returns the raw JSON value of [functionType]. + * Sets [Builder.promptData] to an arbitrary JSON value. * - * Unlike [functionType], this method doesn't throw if the JSON field has an unexpected - * type. + * You should usually call [Builder.promptData] with a well-typed [PromptData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("function_type") - @ExcludeMissing - fun _functionType(): JsonField = functionType + fun promptData(promptData: JsonField) = apply { body.promptData(promptData) } + + /** A list of tags for the prompt */ + fun tags(tags: List?) = apply { body.tags(tags) } + + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) /** - * Returns the raw JSON value of [promptData]. + * Sets [Builder.tags] to an arbitrary JSON value. * - * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.tags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("prompt_data") - @ExcludeMissing - fun _promptData(): JsonField = promptData + fun tags(tags: JsonField>) = apply { body.tags(tags) } /** - * Returns the raw JSON value of [tags]. + * Adds a single [String] to [tags]. * - * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + fun addTag(tag: String) = apply { body.addTag(tag) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var validated: Boolean = false + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - fun validate(): Body = apply { - if (validated) { - return@apply + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - name() - projectId() - slug() - description() - functionType() - promptData().ifPresent { it.validate() } - tags() - validated = true - } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun toBuilder() = Builder().from(this) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - companion object { + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .slug() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - private var name: JsonField? = null - private var projectId: JsonField? = null - private var slug: JsonField? = null - private var description: JsonField = JsonMissing.of() - private var functionType: JsonField = JsonMissing.of() - private var promptData: JsonField = JsonMissing.of() - private var tags: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - projectId = body.projectId - slug = body.slug - description = body.description - functionType = body.functionType - promptData = body.promptData - tags = body.tags.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Name of the prompt */ - fun name(name: String) = name(JsonField.of(name)) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** - * 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 } - - /** Unique identifier for the project that the prompt belongs under */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - - /** - * Sets [Builder.projectId] to an arbitrary JSON value. - * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } - - /** Unique identifier for the prompt */ - fun slug(slug: String) = slug(JsonField.of(slug)) - - /** - * Sets [Builder.slug] to an arbitrary JSON value. - * - * You should usually call [Builder.slug] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun slug(slug: JsonField) = apply { this.slug = slug } - - /** Textual description of the prompt */ - fun description(description: String?) = description(JsonField.ofNullable(description)) - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } - - fun functionType(functionType: FunctionType?) = - functionType(JsonField.ofNullable(functionType)) - - /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ - fun functionType(functionType: Optional) = - functionType(functionType.getOrNull()) - - /** - * Sets [Builder.functionType] to an arbitrary JSON value. - * - * You should usually call [Builder.functionType] with a well-typed [FunctionType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun functionType(functionType: JsonField) = apply { - this.functionType = functionType - } - - /** The prompt, model, and its parameters */ - fun promptData(promptData: PromptData?) = promptData(JsonField.ofNullable(promptData)) - - /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ - fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) - - /** - * Sets [Builder.promptData] to an arbitrary JSON value. - * - * You should usually call [Builder.promptData] with a well-typed [PromptData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun promptData(promptData: JsonField) = apply { - this.promptData = promptData - } + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** A list of tags for the prompt */ - fun tags(tags: List?) = tags(JsonField.ofNullable(tags)) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ - fun tags(tags: Optional>) = tags(tags.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.tags] to an arbitrary JSON value. - * - * You should usually call [Builder.tags] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun tags(tags: JsonField>) = apply { - this.tags = tags.map { it.toMutableList() } - } + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Adds a single [String] to [tags]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addTag(tag: String) = apply { - tags = - (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } - } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .slug() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("name", name), - checkRequired("projectId", projectId), - checkRequired("slug", slug), - description, - functionType, - promptData, - (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && slug == other.slug && description == other.description && functionType == other.functionType && promptData == other.promptData && tags == other.tags && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, projectId, slug, description, functionType, promptData, tags, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{name=$name, projectId=$projectId, slug=$slug, description=$description, functionType=$functionType, promptData=$promptData, tags=$tags, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [PromptReplaceParams]. + * Returns an immutable instance of [PromptReplaceParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java @@ -546,265 +419,433 @@ private constructor( * .projectId() * .slug() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): PromptReplaceParams = + PromptReplaceParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [PromptReplaceParams]. */ - @NoAutoDetect - class Builder internal constructor() { + fun _body(): Body = body - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + override fun _headers(): Headers = additionalHeaders - @JvmSynthetic - internal fun from(promptReplaceParams: PromptReplaceParams) = apply { - body = promptReplaceParams.body.toBuilder() - additionalHeaders = promptReplaceParams.additionalHeaders.toBuilder() - additionalQueryParams = promptReplaceParams.additionalQueryParams.toBuilder() - } + override fun _queryParams(): QueryParams = additionalQueryParams - /** Name of the prompt */ - fun name(name: String) = apply { body.name(name) } + class Body + private constructor( + private val name: JsonField, + private val projectId: JsonField, + private val slug: JsonField, + private val description: JsonField, + private val functionType: JsonField, + private val promptData: JsonField, + private val tags: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") + @ExcludeMissing + projectId: JsonField = JsonMissing.of(), + @JsonProperty("slug") @ExcludeMissing slug: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("function_type") + @ExcludeMissing + functionType: JsonField = JsonMissing.of(), + @JsonProperty("prompt_data") + @ExcludeMissing + promptData: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this(name, projectId, slug, description, functionType, promptData, tags, mutableMapOf()) /** - * Sets [Builder.name] to an arbitrary JSON value. + * Name of the prompt * - * 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. + * @throws BraintrustInvalidDataException 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(name: JsonField) = apply { body.name(name) } - - /** Unique identifier for the project that the prompt belongs under */ - fun projectId(projectId: String) = apply { body.projectId(projectId) } + fun name(): String = name.getRequired("name") /** - * Sets [Builder.projectId] to an arbitrary JSON value. + * Unique identifier for the project that the prompt belongs under * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException 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 projectId(projectId: JsonField) = apply { body.projectId(projectId) } - - /** Unique identifier for the prompt */ - fun slug(slug: String) = apply { body.slug(slug) } + fun projectId(): String = projectId.getRequired("project_id") /** - * Sets [Builder.slug] to an arbitrary JSON value. + * Unique identifier for the prompt * - * You should usually call [Builder.slug] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException 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 slug(slug: JsonField) = apply { body.slug(slug) } - - /** Textual description of the prompt */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + fun slug(): String = slug.getRequired("slug") /** - * Sets [Builder.description] to an arbitrary JSON value. + * Textual description of the prompt * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun description(description: JsonField) = apply { body.description(description) } + fun description(): Optional = description.getOptional("description") - fun functionType(functionType: FunctionType?) = apply { body.functionType(functionType) } + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun functionType(): Optional = functionType.getOptional("function_type") - /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ - fun functionType(functionType: Optional) = - functionType(functionType.getOrNull()) + /** + * The prompt, model, and its parameters + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun promptData(): Optional = promptData.getOptional("prompt_data") /** - * Sets [Builder.functionType] to an arbitrary JSON value. + * A list of tags for the prompt * - * You should usually call [Builder.functionType] with a well-typed [FunctionType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun functionType(functionType: JsonField) = apply { - body.functionType(functionType) - } + fun tags(): Optional> = tags.getOptional("tags") - /** The prompt, model, and its parameters */ - fun promptData(promptData: PromptData?) = apply { body.promptData(promptData) } + /** + * 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 - /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ - fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("project_id") @ExcludeMissing fun _projectId(): JsonField = projectId /** - * Sets [Builder.promptData] to an arbitrary JSON value. + * Returns the raw JSON value of [slug]. * - * You should usually call [Builder.promptData] with a well-typed [PromptData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * Unlike [slug], this method doesn't throw if the JSON field has an unexpected type. */ - fun promptData(promptData: JsonField) = apply { body.promptData(promptData) } + @JsonProperty("slug") @ExcludeMissing fun _slug(): JsonField = slug - /** A list of tags for the prompt */ - fun tags(tags: List?) = apply { body.tags(tags) } + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description - /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ - fun tags(tags: Optional>) = tags(tags.getOrNull()) + /** + * Returns the raw JSON value of [functionType]. + * + * Unlike [functionType], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_type") + @ExcludeMissing + fun _functionType(): JsonField = functionType /** - * Sets [Builder.tags] to an arbitrary JSON value. + * Returns the raw JSON value of [promptData]. * - * You should usually call [Builder.tags] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. */ - fun tags(tags: JsonField>) = apply { body.tags(tags) } + @JsonProperty("prompt_data") + @ExcludeMissing + fun _promptData(): JsonField = promptData /** - * Adds a single [String] to [tags]. + * Returns the raw JSON value of [tags]. * - * @throws IllegalStateException if the field was previously set to a non-list. + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. */ - fun addTag(tag: String) = apply { body.addTag(tag) } + @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + + @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 + * .name() + * .projectId() + * .slug() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var projectId: JsonField? = null + private var slug: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var functionType: JsonField = JsonMissing.of() + private var promptData: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + projectId = body.projectId + slug = body.slug + description = body.description + functionType = body.functionType + promptData = body.promptData + tags = body.tags.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the prompt */ + 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 } + + /** Unique identifier for the project that the prompt belongs under */ + fun projectId(projectId: String) = projectId(JsonField.of(projectId)) + + /** + * Sets [Builder.projectId] to an arbitrary JSON value. + * + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun projectId(projectId: JsonField) = apply { this.projectId = projectId } + + /** Unique identifier for the prompt */ + fun slug(slug: String) = slug(JsonField.of(slug)) + + /** + * Sets [Builder.slug] to an arbitrary JSON value. + * + * You should usually call [Builder.slug] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun slug(slug: JsonField) = apply { this.slug = slug } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) - } + /** Textual description of the prompt */ + fun description(description: String?) = description(JsonField.ofNullable(description)) - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description } - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + fun functionType(functionType: FunctionType?) = + functionType(JsonField.ofNullable(functionType)) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** Alias for calling [Builder.functionType] with `functionType.orElse(null)`. */ + fun functionType(functionType: Optional) = + functionType(functionType.getOrNull()) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Sets [Builder.functionType] to an arbitrary JSON value. + * + * You should usually call [Builder.functionType] with a well-typed [FunctionType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun functionType(functionType: JsonField) = apply { + this.functionType = functionType + } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** The prompt, model, and its parameters */ + fun promptData(promptData: PromptData?) = promptData(JsonField.ofNullable(promptData)) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ + fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * Sets [Builder.promptData] to an arbitrary JSON value. + * + * You should usually call [Builder.promptData] with a well-typed [PromptData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun promptData(promptData: JsonField) = apply { + this.promptData = promptData + } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** A list of tags for the prompt */ + fun tags(tags: List?) = tags(JsonField.ofNullable(tags)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.tags] to an arbitrary JSON value. + * + * You should usually call [Builder.tags] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tags(tags: JsonField>) = apply { + this.tags = tags.map { it.toMutableList() } + } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { + tags = + (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } + } - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * .slug() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("name", name), + checkRequired("projectId", projectId), + checkRequired("slug", slug), + description, + functionType, + promptData, + (tags ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + private var validated: Boolean = false - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun validate(): Body = apply { + if (validated) { + return@apply + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) + name() + projectId() + slug() + description() + functionType().ifPresent { it.validate() } + promptData().ifPresent { it.validate() } + tags() + validated = true } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (slug.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (functionType.asKnown().getOrNull()?.validity() ?: 0) + + (promptData.asKnown().getOrNull()?.validity() ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && slug == other.slug && description == other.description && functionType == other.functionType && promptData == other.promptData && tags == other.tags && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, projectId, slug, description, functionType, promptData, tags, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [PromptReplaceParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .slug() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): PromptReplaceParams = - PromptReplaceParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{name=$name, projectId=$projectId, slug=$slug, description=$description, functionType=$functionType, promptData=$promptData, tags=$tags, additionalProperties=$additionalProperties}" } class FunctionType @JsonCreator private constructor(private val value: JsonField) : @@ -909,6 +950,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): FunctionType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptRetrieveParams.kt index bd674855..b05a03df 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> promptId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [PromptRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var promptId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> promptId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptUpdateParams.kt index 2e6f019a..73422bc0 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptUpdateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptUpdateParams.kt @@ -6,19 +6,18 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -120,207 +119,461 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) - override fun _headers(): Headers = additionalHeaders + companion object { - override fun _queryParams(): QueryParams = additionalQueryParams + /** + * Returns a mutable builder for constructing an instance of [PromptUpdateParams]. + * + * The following fields are required: + * ```java + * .promptId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - fun getPathParam(index: Int): String { - return when (index) { - 0 -> promptId - else -> "" + /** A builder for [PromptUpdateParams]. */ + class Builder internal constructor() { + + private var promptId: 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(promptUpdateParams: PromptUpdateParams) = apply { + promptId = promptUpdateParams.promptId + body = promptUpdateParams.body.toBuilder() + additionalHeaders = promptUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = promptUpdateParams.additionalQueryParams.toBuilder() } - } - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("prompt_data") - @ExcludeMissing - private val promptData: JsonField = JsonMissing.of(), - @JsonProperty("slug") - @ExcludeMissing - private val slug: JsonField = JsonMissing.of(), - @JsonProperty("tags") - @ExcludeMissing - private val tags: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** Prompt id */ + fun promptId(promptId: String) = apply { this.promptId = promptId } /** - * Textual description of the prompt + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [description] + * - [name] + * - [promptData] + * - [slug] + * - [tags] + * - etc. */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun body(body: Body) = apply { this.body = body.toBuilder() } - /** - * Name of the prompt - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + /** Textual description of the prompt */ + fun description(description: String?) = apply { body.description(description) } - /** - * The prompt, model, and its parameters - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun promptData(): Optional = - Optional.ofNullable(promptData.getNullable("prompt_data")) + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) /** - * Unique identifier for the prompt + * Sets [Builder.description] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun slug(): Optional = Optional.ofNullable(slug.getNullable("slug")) + fun description(description: JsonField) = apply { body.description(description) } - /** - * A list of tags for the prompt - * - * @throws BraintrustInvalidDataException 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")) + /** Name of the prompt */ + fun name(name: String?) = apply { body.name(name) } + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) /** - * Returns the raw JSON value of [description]. + * Sets [Builder.name] to an arbitrary JSON value. * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description + fun name(name: JsonField) = apply { body.name(name) } + + /** The prompt, model, and its parameters */ + fun promptData(promptData: PromptData?) = apply { body.promptData(promptData) } + + /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ + fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) /** - * Returns the raw JSON value of [name]. + * Sets [Builder.promptData] to an arbitrary JSON value. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.promptData] with a well-typed [PromptData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun promptData(promptData: JsonField) = apply { body.promptData(promptData) } + + /** Unique identifier for the prompt */ + fun slug(slug: String?) = apply { body.slug(slug) } + + /** Alias for calling [Builder.slug] with `slug.orElse(null)`. */ + fun slug(slug: Optional) = slug(slug.getOrNull()) /** - * Returns the raw JSON value of [promptData]. + * Sets [Builder.slug] to an arbitrary JSON value. * - * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.slug] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("prompt_data") - @ExcludeMissing - fun _promptData(): JsonField = promptData + fun slug(slug: JsonField) = apply { body.slug(slug) } + + /** A list of tags for the prompt */ + fun tags(tags: List?) = apply { body.tags(tags) } + + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) /** - * Returns the raw JSON value of [slug]. + * Sets [Builder.tags] to an arbitrary JSON value. * - * Unlike [slug], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.tags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("slug") @ExcludeMissing fun _slug(): JsonField = slug + fun tags(tags: JsonField>) = apply { body.tags(tags) } /** - * Returns the raw JSON value of [tags]. + * Adds a single [String] to [tags]. * - * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + fun addTag(tag: String) = apply { body.addTag(tag) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var validated: Boolean = false + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - fun validate(): Body = apply { - if (validated) { - return@apply + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - description() - name() - promptData().ifPresent { it.validate() } - slug() - tags() - validated = true - } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun toBuilder() = Builder().from(this) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - companion object { + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Returns a mutable builder for constructing an instance of [Body]. */ - @JvmStatic fun builder() = Builder() + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - /** A builder for [Body]. */ - class Builder internal constructor() { + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - private var description: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var promptData: JsonField = JsonMissing.of() - private var slug: JsonField = JsonMissing.of() - private var tags: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - @JvmSynthetic - internal fun from(body: Body) = apply { - description = body.description - name = body.name - promptData = body.promptData - slug = body.slug - tags = body.tags.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Textual description of the prompt */ - fun description(description: String?) = description(JsonField.ofNullable(description)) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** Name of the prompt */ - fun name(name: String?) = name(JsonField.ofNullable(name)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.name] with `name.orElse(null)`. */ - fun name(name: Optional) = name(name.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * 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 removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - /** The prompt, model, and its parameters */ - fun promptData(promptData: PromptData?) = promptData(JsonField.ofNullable(promptData)) + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ - fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) + 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 [PromptUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .promptId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): PromptUpdateParams = + PromptUpdateParams( + checkRequired("promptId", promptId), + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> promptId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val description: JsonField, + private val name: JsonField, + private val promptData: JsonField, + private val slug: JsonField, + private val tags: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("prompt_data") + @ExcludeMissing + promptData: JsonField = JsonMissing.of(), + @JsonProperty("slug") @ExcludeMissing slug: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this(description, name, promptData, slug, tags, mutableMapOf()) + + /** + * Textual description of the prompt + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * Name of the prompt + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * The prompt, model, and its parameters + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun promptData(): Optional = promptData.getOptional("prompt_data") + + /** + * Unique identifier for the prompt + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun slug(): Optional = slug.getOptional("slug") + + /** + * A list of tags for the prompt + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun tags(): Optional> = tags.getOptional("tags") + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [promptData]. + * + * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prompt_data") + @ExcludeMissing + fun _promptData(): JsonField = promptData + + /** + * Returns the raw JSON value of [slug]. + * + * Unlike [slug], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("slug") @ExcludeMissing fun _slug(): JsonField = slug + + /** + * 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 + + @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]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var description: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var promptData: JsonField = JsonMissing.of() + private var slug: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + description = body.description + name = body.name + promptData = body.promptData + slug = body.slug + tags = body.tags.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Textual description of the prompt */ + fun description(description: String?) = description(JsonField.ofNullable(description)) + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + + /** Name of the prompt */ + 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 } + + /** The prompt, model, and its parameters */ + fun promptData(promptData: PromptData?) = promptData(JsonField.ofNullable(promptData)) + + /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ + fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) /** * Sets [Builder.promptData] to an arbitrary JSON value. @@ -406,279 +659,63 @@ private constructor( promptData, slug, (tags ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply } - return /* spotless:off */ other is Body && description == other.description && name == other.name && promptData == other.promptData && slug == other.slug && tags == other.tags && additionalProperties == other.additionalProperties /* spotless:on */ + description() + name() + promptData().ifPresent { it.validate() } + slug() + tags() + validated = true } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(description, name, promptData, slug, tags, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{description=$description, name=$name, promptData=$promptData, slug=$slug, tags=$tags, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } /** - * Returns a mutable builder for constructing an instance of [PromptUpdateParams]. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * The following fields are required: - * ```java - * .promptId() - * ``` + * Used for best match union deserialization. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [PromptUpdateParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var promptId: 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(promptUpdateParams: PromptUpdateParams) = apply { - promptId = promptUpdateParams.promptId - body = promptUpdateParams.body.toBuilder() - additionalHeaders = promptUpdateParams.additionalHeaders.toBuilder() - additionalQueryParams = promptUpdateParams.additionalQueryParams.toBuilder() - } - - /** Prompt id */ - fun promptId(promptId: String) = apply { this.promptId = promptId } - - /** Textual description of the prompt */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun description(description: JsonField) = apply { body.description(description) } - - /** Name of the prompt */ - fun name(name: String?) = apply { body.name(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 { body.name(name) } - - /** The prompt, model, and its parameters */ - fun promptData(promptData: PromptData?) = apply { body.promptData(promptData) } - - /** Alias for calling [Builder.promptData] with `promptData.orElse(null)`. */ - fun promptData(promptData: Optional) = promptData(promptData.getOrNull()) - - /** - * Sets [Builder.promptData] to an arbitrary JSON value. - * - * You should usually call [Builder.promptData] with a well-typed [PromptData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun promptData(promptData: JsonField) = apply { body.promptData(promptData) } - - /** Unique identifier for the prompt */ - fun slug(slug: String?) = apply { body.slug(slug) } - - /** Alias for calling [Builder.slug] with `slug.orElse(null)`. */ - fun slug(slug: Optional) = slug(slug.getOrNull()) - - /** - * Sets [Builder.slug] to an arbitrary JSON value. - * - * You should usually call [Builder.slug] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun slug(slug: JsonField) = apply { body.slug(slug) } - - /** A list of tags for the prompt */ - fun tags(tags: List?) = apply { body.tags(tags) } - - /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ - fun tags(tags: Optional>) = tags(tags.getOrNull()) - - /** - * Sets [Builder.tags] to an arbitrary JSON value. - * - * You should usually call [Builder.tags] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun tags(tags: JsonField>) = apply { body.tags(tags) } - - /** - * Adds a single [String] to [tags]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addTag(tag: String) = apply { body.addTag(tag) } - - 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) } + internal fun validity(): Int = + (if (description.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (promptData.asKnown().getOrNull()?.validity() ?: 0) + + (if (slug.asKnown().isPresent) 1 else 0) + + (tags.asKnown().getOrNull()?.size ?: 0) - 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) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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) + return /* spotless:off */ other is Body && description == other.description && name == other.name && promptData == other.promptData && slug == other.slug && tags == other.tags && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(description, name, promptData, slug, tags, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [PromptUpdateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .promptId() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): PromptUpdateParams = - PromptUpdateParams( - checkRequired("promptId", promptId), - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{description=$description, name=$name, promptData=$promptData, slug=$slug, tags=$tags, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RepoInfo.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RepoInfo.kt index 0ce351bc..d51766be 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RepoInfo.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RepoInfo.kt @@ -6,57 +6,70 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 /** Metadata about the state of the repo when the experiment was created */ -@NoAutoDetect class RepoInfo -@JsonCreator private constructor( - @JsonProperty("author_email") - @ExcludeMissing - private val authorEmail: JsonField = JsonMissing.of(), - @JsonProperty("author_name") - @ExcludeMissing - private val authorName: JsonField = JsonMissing.of(), - @JsonProperty("branch") - @ExcludeMissing - private val branch: JsonField = JsonMissing.of(), - @JsonProperty("commit") - @ExcludeMissing - private val commit: JsonField = JsonMissing.of(), - @JsonProperty("commit_message") - @ExcludeMissing - private val commitMessage: JsonField = JsonMissing.of(), - @JsonProperty("commit_time") - @ExcludeMissing - private val commitTime: JsonField = JsonMissing.of(), - @JsonProperty("dirty") @ExcludeMissing private val dirty: JsonField = JsonMissing.of(), - @JsonProperty("git_diff") - @ExcludeMissing - private val gitDiff: JsonField = JsonMissing.of(), - @JsonProperty("tag") @ExcludeMissing private val tag: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val authorEmail: JsonField, + private val authorName: JsonField, + private val branch: JsonField, + private val commit: JsonField, + private val commitMessage: JsonField, + private val commitTime: JsonField, + private val dirty: JsonField, + private val gitDiff: JsonField, + private val tag: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("author_email") + @ExcludeMissing + authorEmail: JsonField = JsonMissing.of(), + @JsonProperty("author_name") + @ExcludeMissing + authorName: JsonField = JsonMissing.of(), + @JsonProperty("branch") @ExcludeMissing branch: JsonField = JsonMissing.of(), + @JsonProperty("commit") @ExcludeMissing commit: JsonField = JsonMissing.of(), + @JsonProperty("commit_message") + @ExcludeMissing + commitMessage: JsonField = JsonMissing.of(), + @JsonProperty("commit_time") + @ExcludeMissing + commitTime: JsonField = JsonMissing.of(), + @JsonProperty("dirty") @ExcludeMissing dirty: JsonField = JsonMissing.of(), + @JsonProperty("git_diff") @ExcludeMissing gitDiff: JsonField = JsonMissing.of(), + @JsonProperty("tag") @ExcludeMissing tag: JsonField = JsonMissing.of(), + ) : this( + authorEmail, + authorName, + branch, + commit, + commitMessage, + commitTime, + dirty, + gitDiff, + tag, + mutableMapOf(), + ) + /** * Email of the author of the most recent commit * * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun authorEmail(): Optional = - Optional.ofNullable(authorEmail.getNullable("author_email")) + fun authorEmail(): Optional = authorEmail.getOptional("author_email") /** * Name of the author of the most recent commit @@ -64,7 +77,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun authorName(): Optional = Optional.ofNullable(authorName.getNullable("author_name")) + fun authorName(): Optional = authorName.getOptional("author_name") /** * Name of the branch the most recent commit belongs to @@ -72,7 +85,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun branch(): Optional = Optional.ofNullable(branch.getNullable("branch")) + fun branch(): Optional = branch.getOptional("branch") /** * SHA of most recent commit @@ -80,7 +93,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun commit(): Optional = Optional.ofNullable(commit.getNullable("commit")) + fun commit(): Optional = commit.getOptional("commit") /** * Most recent commit message @@ -88,8 +101,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun commitMessage(): Optional = - Optional.ofNullable(commitMessage.getNullable("commit_message")) + fun commitMessage(): Optional = commitMessage.getOptional("commit_message") /** * Time of the most recent commit @@ -97,7 +109,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun commitTime(): Optional = Optional.ofNullable(commitTime.getNullable("commit_time")) + fun commitTime(): Optional = commitTime.getOptional("commit_time") /** * Whether or not the repo had uncommitted changes when snapshotted @@ -105,7 +117,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun dirty(): Optional = Optional.ofNullable(dirty.getNullable("dirty")) + fun dirty(): Optional = dirty.getOptional("dirty") /** * If the repo was dirty when run, this includes the diff between the current state of the repo @@ -114,7 +126,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun gitDiff(): Optional = Optional.ofNullable(gitDiff.getNullable("git_diff")) + fun gitDiff(): Optional = gitDiff.getOptional("git_diff") /** * Name of the tag on the most recent commit @@ -122,7 +134,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun tag(): Optional = Optional.ofNullable(tag.getNullable("tag")) + fun tag(): Optional = tag.getOptional("tag") /** * Returns the raw JSON value of [authorEmail]. @@ -191,28 +203,15 @@ private constructor( */ @JsonProperty("tag") @ExcludeMissing fun _tag(): JsonField = tag + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): RepoInfo = apply { - if (validated) { - return@apply - } - - authorEmail() - authorName() - branch() - commit() - commitMessage() - commitTime() - dirty() - gitDiff() - tag() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -429,10 +428,54 @@ private constructor( dirty, gitDiff, tag, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): RepoInfo = apply { + if (validated) { + return@apply + } + + authorEmail() + authorName() + branch() + commit() + commitMessage() + commitTime() + dirty() + gitDiff() + tag() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (authorEmail.asKnown().isPresent) 1 else 0) + + (if (authorName.asKnown().isPresent) 1 else 0) + + (if (branch.asKnown().isPresent) 1 else 0) + + (if (commit.asKnown().isPresent) 1 else 0) + + (if (commitMessage.asKnown().isPresent) 1 else 0) + + (if (commitTime.asKnown().isPresent) 1 else 0) + + (if (dirty.asKnown().isPresent) 1 else 0) + + (if (gitDiff.asKnown().isPresent) 1 else 0) + + (if (tag.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Role.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Role.kt index 43105f4e..f55b44e3 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Role.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Role.kt @@ -6,10 +6,8 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter @@ -17,6 +15,7 @@ import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -26,34 +25,54 @@ import kotlin.jvm.optionals.getOrNull * * Roles can consist of individual permissions, as well as a set of roles they inherit from */ -@NoAutoDetect class Role -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("deleted_at") - @ExcludeMissing - private val deletedAt: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("member_permissions") - @ExcludeMissing - private val memberPermissions: JsonField> = JsonMissing.of(), - @JsonProperty("member_roles") - @ExcludeMissing - private val memberRoles: JsonField> = JsonMissing.of(), - @JsonProperty("org_id") @ExcludeMissing private val orgId: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val name: JsonField, + private val created: JsonField, + private val deletedAt: JsonField, + private val description: JsonField, + private val memberPermissions: JsonField>, + private val memberRoles: JsonField>, + private val orgId: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("deleted_at") + @ExcludeMissing + deletedAt: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("member_permissions") + @ExcludeMissing + memberPermissions: JsonField> = JsonMissing.of(), + @JsonProperty("member_roles") + @ExcludeMissing + memberRoles: JsonField> = JsonMissing.of(), + @JsonProperty("org_id") @ExcludeMissing orgId: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this( + id, + name, + created, + deletedAt, + description, + memberPermissions, + memberRoles, + orgId, + userId, + mutableMapOf(), + ) + /** * Unique identifier for the role * @@ -76,7 +95,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Date of role deletion, or null if the role is still active @@ -84,8 +103,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun deletedAt(): Optional = - Optional.ofNullable(deletedAt.getNullable("deleted_at")) + fun deletedAt(): Optional = deletedAt.getOptional("deleted_at") /** * Textual description of the role @@ -93,8 +111,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun description(): Optional = description.getOptional("description") /** * (permission, restrict_object_type) tuples which belong to this role @@ -103,7 +120,7 @@ private constructor( * server responded with an unexpected value). */ fun memberPermissions(): Optional> = - Optional.ofNullable(memberPermissions.getNullable("member_permissions")) + memberPermissions.getOptional("member_permissions") /** * Ids of the roles this role inherits from @@ -114,8 +131,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun memberRoles(): Optional> = - Optional.ofNullable(memberRoles.getNullable("member_roles")) + fun memberRoles(): Optional> = memberRoles.getOptional("member_roles") /** * Unique id for the organization that the role belongs under @@ -128,7 +144,7 @@ private constructor( * @throws BraintrustInvalidDataException 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 orgId(): Optional = orgId.getOptional("org_id") /** * Identifies the user who created the role @@ -136,7 +152,7 @@ private constructor( * @throws BraintrustInvalidDataException 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 [id]. @@ -208,28 +224,15 @@ private constructor( */ @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 = additionalProperties - - private var validated: Boolean = false - - fun validate(): Role = apply { - if (validated) { - return@apply - } - - id() - name() - created() - deletedAt() - description() - memberPermissions().ifPresent { it.forEach { it.validate() } } - memberRoles() - orgId() - userId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -485,24 +488,71 @@ private constructor( (memberRoles ?: JsonMissing.of()).map { it.toImmutable() }, orgId, userId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Role = apply { + if (validated) { + return@apply + } + + id() + name() + created() + deletedAt() + description() + memberPermissions().ifPresent { it.forEach { it.validate() } } + memberRoles() + orgId() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (deletedAt.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (memberPermissions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (memberRoles.asKnown().getOrNull()?.size ?: 0) + + (if (orgId.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + class MemberPermission - @JsonCreator private constructor( - @JsonProperty("permission") - @ExcludeMissing - private val permission: JsonField = JsonMissing.of(), - @JsonProperty("restrict_object_type") - @ExcludeMissing - private val restrictObjectType: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val permission: JsonField, + private val restrictObjectType: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("permission") + @ExcludeMissing + permission: JsonField = JsonMissing.of(), + @JsonProperty("restrict_object_type") + @ExcludeMissing + restrictObjectType: JsonField = JsonMissing.of(), + ) : this(permission, restrictObjectType, mutableMapOf()) + /** * Each permission permits a certain type of operation on an object in the system * @@ -520,7 +570,7 @@ private constructor( * the server responded with an unexpected value). */ fun restrictObjectType(): Optional = - Optional.ofNullable(restrictObjectType.getNullable("restrict_object_type")) + restrictObjectType.getOptional("restrict_object_type") /** * Returns the raw JSON value of [permission]. @@ -541,21 +591,15 @@ private constructor( @ExcludeMissing fun _restrictObjectType(): JsonField = restrictObjectType + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): MemberPermission = apply { - if (validated) { - return@apply - } - - permission() - restrictObjectType() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -662,10 +706,41 @@ private constructor( MemberPermission( checkRequired("permission", permission), restrictObjectType, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): MemberPermission = apply { + if (validated) { + return@apply + } + + permission().validate() + restrictObjectType().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (permission.asKnown().getOrNull()?.validity() ?: 0) + + (restrictObjectType.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleCreateParams.kt index d33aa0b9..4e8526c6 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleCreateParams.kt @@ -6,19 +6,18 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -121,635 +120,679 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun toBuilder() = Builder().from(this) - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("member_permissions") - @ExcludeMissing - private val memberPermissions: JsonField> = JsonMissing.of(), - @JsonProperty("member_roles") - @ExcludeMissing - private val memberRoles: JsonField> = JsonMissing.of(), - @JsonProperty("org_name") - @ExcludeMissing - private val orgName: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + companion object { /** - * Name of the role + * Returns a mutable builder for constructing an instance of [RoleCreateParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .name() + * ``` */ - fun name(): String = name.getRequired("name") + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RoleCreateParams]. */ + 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(roleCreateParams: RoleCreateParams) = apply { + body = roleCreateParams.body.toBuilder() + additionalHeaders = roleCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = roleCreateParams.additionalQueryParams.toBuilder() + } /** - * Textual description of the role + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [name] + * - [description] + * - [memberPermissions] + * - [memberRoles] + * - [orgName] + * - etc. */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the role */ + fun name(name: String) = apply { body.name(name) } /** - * (permission, restrict_object_type) tuples which belong to this role + * Sets [Builder.name] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected 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 memberPermissions(): Optional> = - Optional.ofNullable(memberPermissions.getNullable("member_permissions")) + fun name(name: JsonField) = apply { body.name(name) } + + /** Textual description of the role */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) /** - * Ids of the roles this role inherits from - * - * An inheriting role has all the permissions contained in its member roles, as well as all - * of their inherited permissions + * Sets [Builder.description] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun memberRoles(): Optional> = - Optional.ofNullable(memberRoles.getNullable("member_roles")) + fun description(description: JsonField) = apply { body.description(description) } + + /** (permission, restrict_object_type) tuples which belong to this role */ + fun memberPermissions(memberPermissions: List?) = apply { + body.memberPermissions(memberPermissions) + } + + /** Alias for calling [Builder.memberPermissions] with `memberPermissions.orElse(null)`. */ + fun memberPermissions(memberPermissions: Optional>) = + memberPermissions(memberPermissions.getOrNull()) /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the role belongs in. + * Sets [Builder.memberPermissions] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.memberPermissions] with a well-typed + * `List` value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. */ - fun orgName(): Optional = Optional.ofNullable(orgName.getNullable("org_name")) + fun memberPermissions(memberPermissions: JsonField>) = apply { + body.memberPermissions(memberPermissions) + } /** - * Returns the raw JSON value of [name]. + * Adds a single [MemberPermission] to [memberPermissions]. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun addMemberPermission(memberPermission: MemberPermission) = apply { + body.addMemberPermission(memberPermission) + } /** - * Returns the raw JSON value of [description]. + * Ids of the roles this role inherits from * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * An inheriting role has all the permissions contained in its member roles, as well as all + * of their inherited permissions */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description + fun memberRoles(memberRoles: List?) = apply { body.memberRoles(memberRoles) } + + /** Alias for calling [Builder.memberRoles] with `memberRoles.orElse(null)`. */ + fun memberRoles(memberRoles: Optional>) = memberRoles(memberRoles.getOrNull()) /** - * Returns the raw JSON value of [memberPermissions]. + * Sets [Builder.memberRoles] to an arbitrary JSON value. * - * Unlike [memberPermissions], this method doesn't throw if the JSON field has an unexpected - * type. + * You should usually call [Builder.memberRoles] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("member_permissions") - @ExcludeMissing - fun _memberPermissions(): JsonField> = memberPermissions + fun memberRoles(memberRoles: JsonField>) = apply { + body.memberRoles(memberRoles) + } /** - * Returns the raw JSON value of [memberRoles]. + * Adds a single [String] to [memberRoles]. * - * Unlike [memberRoles], this method doesn't throw if the JSON field has an unexpected type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("member_roles") - @ExcludeMissing - fun _memberRoles(): JsonField> = memberRoles + fun addMemberRole(memberRole: String) = apply { body.addMemberRole(memberRole) } /** - * Returns the raw JSON value of [orgName]. - * - * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the role belongs in. */ - @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun orgName(orgName: String?) = apply { body.orgName(orgName) } - private var validated: Boolean = false + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) - fun validate(): Body = apply { - if (validated) { - return@apply - } + /** + * Sets [Builder.orgName] to an arbitrary JSON value. + * + * You should usually call [Builder.orgName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun orgName(orgName: JsonField) = apply { body.orgName(orgName) } - name() - description() - memberPermissions().ifPresent { it.forEach { it.validate() } } - memberRoles() - orgName() - validated = true + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) } - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) } - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var name: JsonField? = null - private var description: JsonField = JsonMissing.of() - private var memberPermissions: JsonField>? = null - private var memberRoles: JsonField>? = null - private var orgName: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - description = body.description - memberPermissions = body.memberPermissions.map { it.toMutableList() } - memberRoles = body.memberRoles.map { it.toMutableList() } - orgName = body.orgName - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** Name of the role */ - 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 } - - /** Textual description of the role */ - fun description(description: String?) = description(JsonField.ofNullable(description)) - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - /** (permission, restrict_object_type) tuples which belong to this role */ - fun memberPermissions(memberPermissions: List?) = - memberPermissions(JsonField.ofNullable(memberPermissions)) - - /** - * Alias for calling [Builder.memberPermissions] with `memberPermissions.orElse(null)`. - */ - fun memberPermissions(memberPermissions: Optional>) = - memberPermissions(memberPermissions.getOrNull()) + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - /** - * Sets [Builder.memberPermissions] to an arbitrary JSON value. - * - * You should usually call [Builder.memberPermissions] with a well-typed - * `List` value instead. This method is primarily for setting the - * field to an undocumented or not yet supported value. - */ - fun memberPermissions(memberPermissions: JsonField>) = apply { - this.memberPermissions = memberPermissions.map { it.toMutableList() } - } + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** - * Adds a single [MemberPermission] to [memberPermissions]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addMemberPermission(memberPermission: MemberPermission) = apply { - memberPermissions = - (memberPermissions ?: JsonField.of(mutableListOf())).also { - checkKnown("memberPermissions", it).add(memberPermission) - } - } + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * Ids of the roles this role inherits from - * - * An inheriting role has all the permissions contained in its member roles, as well as - * all of their inherited permissions - */ - fun memberRoles(memberRoles: List?) = - memberRoles(JsonField.ofNullable(memberRoles)) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Alias for calling [Builder.memberRoles] with `memberRoles.orElse(null)`. */ - fun memberRoles(memberRoles: Optional>) = - memberRoles(memberRoles.getOrNull()) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** - * Sets [Builder.memberRoles] to an arbitrary JSON value. - * - * You should usually call [Builder.memberRoles] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun memberRoles(memberRoles: JsonField>) = apply { - this.memberRoles = memberRoles.map { it.toMutableList() } - } + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** - * Adds a single [String] to [memberRoles]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addMemberRole(memberRole: String) = apply { - memberRoles = - (memberRoles ?: JsonField.of(mutableListOf())).also { - checkKnown("memberRoles", it).add(memberRole) - } - } + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the role belongs in. - */ - fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ - fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * Sets [Builder.orgName] to an arbitrary JSON value. - * - * You should usually call [Builder.orgName] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun orgName(orgName: JsonField) = apply { this.orgName = orgName } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("name", name), - description, - (memberPermissions ?: JsonMissing.of()).map { it.toImmutable() }, - (memberRoles ?: JsonMissing.of()).map { it.toImmutable() }, - orgName, - additionalProperties.toImmutable(), - ) + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + 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) } - return /* spotless:off */ other is Body && name == other.name && description == other.description && memberPermissions == other.memberPermissions && memberRoles == other.memberRoles && orgName == other.orgName && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, description, memberPermissions, memberRoles, orgName, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{name=$name, description=$description, memberPermissions=$memberPermissions, memberRoles=$memberRoles, orgName=$orgName, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [RoleCreateParams]. + * Returns an immutable instance of [RoleCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java * .name() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): RoleCreateParams = + RoleCreateParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) } - /** A builder for [RoleCreateParams]. */ - @NoAutoDetect - 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(roleCreateParams: RoleCreateParams) = apply { - body = roleCreateParams.body.toBuilder() - additionalHeaders = roleCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = roleCreateParams.additionalQueryParams.toBuilder() - } + fun _body(): Body = body - /** Name of the role */ - fun name(name: String) = apply { body.name(name) } + override fun _headers(): Headers = additionalHeaders - /** - * 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 { body.name(name) } + override fun _queryParams(): QueryParams = additionalQueryParams - /** Textual description of the role */ - fun description(description: String?) = apply { body.description(description) } + class Body + private constructor( + private val name: JsonField, + private val description: JsonField, + private val memberPermissions: JsonField>, + private val memberRoles: JsonField>, + private val orgName: JsonField, + private val additionalProperties: MutableMap, + ) { - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("member_permissions") + @ExcludeMissing + memberPermissions: JsonField> = JsonMissing.of(), + @JsonProperty("member_roles") + @ExcludeMissing + memberRoles: JsonField> = JsonMissing.of(), + @JsonProperty("org_name") @ExcludeMissing orgName: JsonField = JsonMissing.of(), + ) : this(name, description, memberPermissions, memberRoles, orgName, mutableMapOf()) /** - * Sets [Builder.description] to an arbitrary JSON value. + * Name of the role * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException 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 description(description: JsonField) = apply { body.description(description) } - - /** (permission, restrict_object_type) tuples which belong to this role */ - fun memberPermissions(memberPermissions: List?) = apply { - body.memberPermissions(memberPermissions) - } - - /** Alias for calling [Builder.memberPermissions] with `memberPermissions.orElse(null)`. */ - fun memberPermissions(memberPermissions: Optional>) = - memberPermissions(memberPermissions.getOrNull()) + fun name(): String = name.getRequired("name") /** - * Sets [Builder.memberPermissions] to an arbitrary JSON value. + * Textual description of the role * - * You should usually call [Builder.memberPermissions] with a well-typed - * `List` value instead. This method is primarily for setting the field to - * an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun memberPermissions(memberPermissions: JsonField>) = apply { - body.memberPermissions(memberPermissions) - } + fun description(): Optional = description.getOptional("description") /** - * Adds a single [MemberPermission] to [memberPermissions]. + * (permission, restrict_object_type) tuples which belong to this role * - * @throws IllegalStateException if the field was previously set to a non-list. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun addMemberPermission(memberPermission: MemberPermission) = apply { - body.addMemberPermission(memberPermission) - } + fun memberPermissions(): Optional> = + memberPermissions.getOptional("member_permissions") /** * Ids of the roles this role inherits from * * An inheriting role has all the permissions contained in its member roles, as well as all * of their inherited permissions + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun memberRoles(memberRoles: List?) = apply { body.memberRoles(memberRoles) } + fun memberRoles(): Optional> = memberRoles.getOptional("member_roles") - /** Alias for calling [Builder.memberRoles] with `memberRoles.orElse(null)`. */ - fun memberRoles(memberRoles: Optional>) = memberRoles(memberRoles.getOrNull()) + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the role belongs in. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun orgName(): Optional = orgName.getOptional("org_name") /** - * Sets [Builder.memberRoles] to an arbitrary JSON value. + * Returns the raw JSON value of [name]. * - * You should usually call [Builder.memberRoles] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. */ - fun memberRoles(memberRoles: JsonField>) = apply { - body.memberRoles(memberRoles) - } + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name /** - * Adds a single [String] to [memberRoles]. + * Returns the raw JSON value of [description]. * - * @throws IllegalStateException if the field was previously set to a non-list. + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. */ - fun addMemberRole(memberRole: String) = apply { body.addMemberRole(memberRole) } + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the role belongs in. + * Returns the raw JSON value of [memberPermissions]. + * + * Unlike [memberPermissions], this method doesn't throw if the JSON field has an unexpected + * type. */ - fun orgName(orgName: String?) = apply { body.orgName(orgName) } + @JsonProperty("member_permissions") + @ExcludeMissing + fun _memberPermissions(): JsonField> = memberPermissions - /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ - fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + /** + * Returns the raw JSON value of [memberRoles]. + * + * Unlike [memberRoles], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("member_roles") + @ExcludeMissing + fun _memberRoles(): JsonField> = memberRoles /** - * Sets [Builder.orgName] to an arbitrary JSON value. + * Returns the raw JSON value of [orgName]. * - * You should usually call [Builder.orgName] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. */ - fun orgName(orgName: JsonField) = apply { body.orgName(orgName) } + @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(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 + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var memberPermissions: JsonField>? = null + private var memberRoles: JsonField>? = null + private var orgName: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + description = body.description + memberPermissions = body.memberPermissions.map { it.toMutableList() } + memberRoles = body.memberRoles.map { it.toMutableList() } + orgName = body.orgName + additionalProperties = body.additionalProperties.toMutableMap() } - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** Name of the role */ + fun name(name: String) = name(JsonField.of(name)) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** + * 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 } + + /** Textual description of the role */ + fun description(description: String?) = description(JsonField.ofNullable(description)) + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + + /** (permission, restrict_object_type) tuples which belong to this role */ + fun memberPermissions(memberPermissions: List?) = + memberPermissions(JsonField.ofNullable(memberPermissions)) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Alias for calling [Builder.memberPermissions] with `memberPermissions.orElse(null)`. + */ + fun memberPermissions(memberPermissions: Optional>) = + memberPermissions(memberPermissions.getOrNull()) - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Sets [Builder.memberPermissions] to an arbitrary JSON value. + * + * You should usually call [Builder.memberPermissions] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun memberPermissions(memberPermissions: JsonField>) = apply { + this.memberPermissions = memberPermissions.map { it.toMutableList() } + } - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** + * Adds a single [MemberPermission] to [memberPermissions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMemberPermission(memberPermission: MemberPermission) = apply { + memberPermissions = + (memberPermissions ?: JsonField.of(mutableListOf())).also { + checkKnown("memberPermissions", it).add(memberPermission) + } + } - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * Ids of the roles this role inherits from + * + * An inheriting role has all the permissions contained in its member roles, as well as + * all of their inherited permissions + */ + fun memberRoles(memberRoles: List?) = + memberRoles(JsonField.ofNullable(memberRoles)) - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.memberRoles] with `memberRoles.orElse(null)`. */ + fun memberRoles(memberRoles: Optional>) = + memberRoles(memberRoles.getOrNull()) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Sets [Builder.memberRoles] to an arbitrary JSON value. + * + * You should usually call [Builder.memberRoles] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun memberRoles(memberRoles: JsonField>) = apply { + this.memberRoles = memberRoles.map { it.toMutableList() } + } - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Adds a single [String] to [memberRoles]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMemberRole(memberRole: String) = apply { + memberRoles = + (memberRoles ?: JsonField.of(mutableListOf())).also { + checkKnown("memberRoles", it).add(memberRole) + } + } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the role belongs in. + */ + fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.orgName] to an arbitrary JSON value. + * + * You should usually call [Builder.orgName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun orgName(orgName: JsonField) = apply { this.orgName = orgName } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("name", name), + description, + (memberPermissions ?: JsonMissing.of()).map { it.toImmutable() }, + (memberRoles ?: JsonMissing.of()).map { it.toImmutable() }, + orgName, + additionalProperties.toMutableMap(), + ) } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + private var validated: Boolean = false - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun validate(): Body = apply { + if (validated) { + return@apply } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) + name() + description() + memberPermissions().ifPresent { it.forEach { it.validate() } } + memberRoles() + orgName() + validated = true } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (memberPermissions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (memberRoles.asKnown().getOrNull()?.size ?: 0) + + (if (orgName.asKnown().isPresent) 1 else 0) - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + return /* spotless:off */ other is Body && name == other.name && description == other.description && memberPermissions == other.memberPermissions && memberRoles == other.memberRoles && orgName == other.orgName && additionalProperties == other.additionalProperties /* spotless:on */ } - /** - * Returns an immutable instance of [RoleCreateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): RoleCreateParams = - RoleCreateParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, description, memberPermissions, memberRoles, orgName, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, description=$description, memberPermissions=$memberPermissions, memberRoles=$memberRoles, orgName=$orgName, additionalProperties=$additionalProperties}" } - @NoAutoDetect class MemberPermission - @JsonCreator private constructor( - @JsonProperty("permission") - @ExcludeMissing - private val permission: JsonField = JsonMissing.of(), - @JsonProperty("restrict_object_type") - @ExcludeMissing - private val restrictObjectType: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val permission: JsonField, + private val restrictObjectType: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("permission") + @ExcludeMissing + permission: JsonField = JsonMissing.of(), + @JsonProperty("restrict_object_type") + @ExcludeMissing + restrictObjectType: JsonField = JsonMissing.of(), + ) : this(permission, restrictObjectType, mutableMapOf()) + /** * Each permission permits a certain type of operation on an object in the system * @@ -767,7 +810,7 @@ private constructor( * the server responded with an unexpected value). */ fun restrictObjectType(): Optional = - Optional.ofNullable(restrictObjectType.getNullable("restrict_object_type")) + restrictObjectType.getOptional("restrict_object_type") /** * Returns the raw JSON value of [permission]. @@ -788,21 +831,15 @@ private constructor( @ExcludeMissing fun _restrictObjectType(): JsonField = restrictObjectType + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): MemberPermission = apply { - if (validated) { - return@apply - } - - permission() - restrictObjectType() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -909,10 +946,41 @@ private constructor( MemberPermission( checkRequired("permission", permission), restrictObjectType, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): MemberPermission = apply { + if (validated) { + return@apply + } + + permission().validate() + restrictObjectType().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (permission.asKnown().getOrNull()?.validity() ?: 0) + + (restrictObjectType.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleDeleteParams.kt index 9136f6ee..596b4e90 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleDeleteParams.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,26 +23,11 @@ private constructor( /** Role id */ fun roleId(): String = roleId - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> roleId - else -> "" - } - } + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -61,7 +45,6 @@ private constructor( } /** A builder for [RoleDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var roleId: String? = null @@ -221,6 +204,19 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> roleId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListPage.kt index 9cae9580..c9437627 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListPage.kt @@ -2,161 +2,115 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.RoleService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all roles. The roles are sorted by creation date, with the most recently-created roles - * coming first - */ +/** @see [RoleService.list] */ class RoleListPage private constructor( - private val rolesService: RoleService, + private val service: RoleService, private val params: RoleListParams, - private val response: Response, + private val response: RoleListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [RoleListPageResponse], but gracefully handles missing data. + * + * @see [RoleListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is RoleListPage && rolesService == other.rolesService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(rolesService, params, response) /* spotless:on */ - - override fun toString() = - "RoleListPage{rolesService=$rolesService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - RoleListParams.builder().from(params).endingBefore(objects().first().id()).build() - ) - } else { - Optional.of( - RoleListParams.builder().from(params).startingAfter(objects().last().id()).build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { rolesService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(rolesService: RoleService, params: RoleListParams, response: Response) = - RoleListPage(rolesService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): RoleListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): RoleListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [RoleListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [RoleListPage]. */ + class Builder internal constructor() { - companion object { + private var service: RoleService? = null + private var params: RoleListParams? = null + private var response: RoleListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [RoleListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(roleListPage: RoleListPage) = apply { + service = roleListPage.service + params = roleListPage.params + response = roleListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: RoleService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: RoleListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: RoleListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [RoleListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RoleListPage = + RoleListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: RoleListPage) : Iterable { @@ -177,4 +131,16 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is RoleListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = "RoleListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListPageAsync.kt index 8e13282e..11469901 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListPageAsync.kt @@ -2,163 +2,119 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.RoleServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all roles. The roles are sorted by creation date, with the most recently-created roles - * coming first - */ +/** @see [RoleServiceAsync.list] */ class RoleListPageAsync private constructor( - private val rolesService: RoleServiceAsync, + private val service: RoleServiceAsync, private val params: RoleListParams, - private val response: Response, + private val response: RoleListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [RoleListPageResponse], but gracefully handles missing data. + * + * @see [RoleListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is RoleListPageAsync && rolesService == other.rolesService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(rolesService, params, response) /* spotless:on */ - - override fun toString() = - "RoleListPageAsync{rolesService=$rolesService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - RoleListParams.builder().from(params).endingBefore(objects().first().id()).build() - ) - } else { - Optional.of( - RoleListParams.builder().from(params).startingAfter(objects().last().id()).build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { rolesService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(rolesService: RoleServiceAsync, params: RoleListParams, response: Response) = - RoleListPageAsync(rolesService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): RoleListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): RoleListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [RoleListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [RoleListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: RoleServiceAsync? = null + private var params: RoleListParams? = null + private var response: RoleListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [RoleListPageAsync]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(roleListPageAsync: RoleListPageAsync) = apply { + service = roleListPageAsync.service + params = roleListPageAsync.params + response = roleListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: RoleServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: RoleListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: RoleListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [RoleListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RoleListPageAsync = + RoleListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: RoleListPageAsync) { @@ -186,4 +142,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is RoleListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "RoleListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListPageResponse.kt new file mode 100644 index 00000000..083c5ccd --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListPageResponse.kt @@ -0,0 +1,192 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class RoleListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") @ExcludeMissing objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of role objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [RoleListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RoleListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(roleListPageResponse: RoleListPageResponse) = apply { + objects = roleListPageResponse.objects.map { it.toMutableList() } + additionalProperties = roleListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of role objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [Role] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: Role) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RoleListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RoleListPageResponse = + RoleListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): RoleListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is RoleListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RoleListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListParams.kt index 333d1d99..f90f054c 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListParams.kt @@ -2,22 +2,10 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -75,31 +63,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - endingBefore?.let { put("ending_before", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - orgName?.let { put("org_name", it) } - roleName?.let { put("role_name", it) } - startingAfter?.let { put("starting_after", it) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -111,7 +74,6 @@ private constructor( } /** A builder for [RoleListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var endingBefore: String? = null @@ -316,17 +278,39 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + endingBefore?.let { put("ending_before", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + orgName?.let { put("org_name", it) } + roleName?.let { put("role_name", it) } + startingAfter?.let { put("starting_after", it) } + putAll(additionalQueryParams) + } + .build() + /** * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -341,15 +325,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -365,7 +346,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -382,51 +362,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleReplaceParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleReplaceParams.kt index 97635d9d..791e3fd8 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleReplaceParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleReplaceParams.kt @@ -6,19 +6,18 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -121,639 +120,683 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun toBuilder() = Builder().from(this) - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("member_permissions") - @ExcludeMissing - private val memberPermissions: JsonField> = JsonMissing.of(), - @JsonProperty("member_roles") - @ExcludeMissing - private val memberRoles: JsonField> = JsonMissing.of(), - @JsonProperty("org_name") - @ExcludeMissing - private val orgName: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + companion object { /** - * Name of the role + * Returns a mutable builder for constructing an instance of [RoleReplaceParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .name() + * ``` */ - fun name(): String = name.getRequired("name") + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RoleReplaceParams]. */ + 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(roleReplaceParams: RoleReplaceParams) = apply { + body = roleReplaceParams.body.toBuilder() + additionalHeaders = roleReplaceParams.additionalHeaders.toBuilder() + additionalQueryParams = roleReplaceParams.additionalQueryParams.toBuilder() + } /** - * Textual description of the role + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [name] + * - [description] + * - [memberPermissions] + * - [memberRoles] + * - [orgName] + * - etc. */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the role */ + fun name(name: String) = apply { body.name(name) } /** - * (permission, restrict_object_type) tuples which belong to this role + * Sets [Builder.name] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected 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 memberPermissions(): Optional> = - Optional.ofNullable(memberPermissions.getNullable("member_permissions")) + fun name(name: JsonField) = apply { body.name(name) } + + /** Textual description of the role */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) /** - * Ids of the roles this role inherits from - * - * An inheriting role has all the permissions contained in its member roles, as well as all - * of their inherited permissions + * Sets [Builder.description] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun memberRoles(): Optional> = - Optional.ofNullable(memberRoles.getNullable("member_roles")) + fun description(description: JsonField) = apply { body.description(description) } + + /** (permission, restrict_object_type) tuples which belong to this role */ + fun memberPermissions(memberPermissions: List?) = apply { + body.memberPermissions(memberPermissions) + } + + /** Alias for calling [Builder.memberPermissions] with `memberPermissions.orElse(null)`. */ + fun memberPermissions(memberPermissions: Optional>) = + memberPermissions(memberPermissions.getOrNull()) /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the role belongs in. + * Sets [Builder.memberPermissions] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.memberPermissions] with a well-typed + * `List` value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. */ - fun orgName(): Optional = Optional.ofNullable(orgName.getNullable("org_name")) + fun memberPermissions(memberPermissions: JsonField>) = apply { + body.memberPermissions(memberPermissions) + } /** - * Returns the raw JSON value of [name]. + * Adds a single [MemberPermission] to [memberPermissions]. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun addMemberPermission(memberPermission: MemberPermission) = apply { + body.addMemberPermission(memberPermission) + } /** - * Returns the raw JSON value of [description]. + * Ids of the roles this role inherits from * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * An inheriting role has all the permissions contained in its member roles, as well as all + * of their inherited permissions */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description + fun memberRoles(memberRoles: List?) = apply { body.memberRoles(memberRoles) } + + /** Alias for calling [Builder.memberRoles] with `memberRoles.orElse(null)`. */ + fun memberRoles(memberRoles: Optional>) = memberRoles(memberRoles.getOrNull()) /** - * Returns the raw JSON value of [memberPermissions]. + * Sets [Builder.memberRoles] to an arbitrary JSON value. * - * Unlike [memberPermissions], this method doesn't throw if the JSON field has an unexpected - * type. + * You should usually call [Builder.memberRoles] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("member_permissions") - @ExcludeMissing - fun _memberPermissions(): JsonField> = memberPermissions + fun memberRoles(memberRoles: JsonField>) = apply { + body.memberRoles(memberRoles) + } /** - * Returns the raw JSON value of [memberRoles]. + * Adds a single [String] to [memberRoles]. * - * Unlike [memberRoles], this method doesn't throw if the JSON field has an unexpected type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("member_roles") - @ExcludeMissing - fun _memberRoles(): JsonField> = memberRoles + fun addMemberRole(memberRole: String) = apply { body.addMemberRole(memberRole) } /** - * Returns the raw JSON value of [orgName]. - * - * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the role belongs in. */ - @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun orgName(orgName: String?) = apply { body.orgName(orgName) } - private var validated: Boolean = false + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) - fun validate(): Body = apply { - if (validated) { - return@apply - } + /** + * Sets [Builder.orgName] to an arbitrary JSON value. + * + * You should usually call [Builder.orgName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun orgName(orgName: JsonField) = apply { body.orgName(orgName) } - name() - description() - memberPermissions().ifPresent { it.forEach { it.validate() } } - memberRoles() - orgName() - validated = true + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) } - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) } - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var name: JsonField? = null - private var description: JsonField = JsonMissing.of() - private var memberPermissions: JsonField>? = null - private var memberRoles: JsonField>? = null - private var orgName: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - description = body.description - memberPermissions = body.memberPermissions.map { it.toMutableList() } - memberRoles = body.memberRoles.map { it.toMutableList() } - orgName = body.orgName - additionalProperties = body.additionalProperties.toMutableMap() + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - /** Name of the role */ - 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 } - - /** Textual description of the role */ - fun description(description: String?) = description(JsonField.ofNullable(description)) - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** (permission, restrict_object_type) tuples which belong to this role */ - fun memberPermissions(memberPermissions: List?) = - memberPermissions(JsonField.ofNullable(memberPermissions)) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * Alias for calling [Builder.memberPermissions] with `memberPermissions.orElse(null)`. - */ - fun memberPermissions(memberPermissions: Optional>) = - memberPermissions(memberPermissions.getOrNull()) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * Sets [Builder.memberPermissions] to an arbitrary JSON value. - * - * You should usually call [Builder.memberPermissions] with a well-typed - * `List` value instead. This method is primarily for setting the - * field to an undocumented or not yet supported value. - */ - fun memberPermissions(memberPermissions: JsonField>) = apply { - this.memberPermissions = memberPermissions.map { it.toMutableList() } - } + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** - * Adds a single [MemberPermission] to [memberPermissions]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addMemberPermission(memberPermission: MemberPermission) = apply { - memberPermissions = - (memberPermissions ?: JsonField.of(mutableListOf())).also { - checkKnown("memberPermissions", it).add(memberPermission) - } - } + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** - * Ids of the roles this role inherits from - * - * An inheriting role has all the permissions contained in its member roles, as well as - * all of their inherited permissions - */ - fun memberRoles(memberRoles: List?) = - memberRoles(JsonField.ofNullable(memberRoles)) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.memberRoles] with `memberRoles.orElse(null)`. */ - fun memberRoles(memberRoles: Optional>) = - memberRoles(memberRoles.getOrNull()) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** - * Sets [Builder.memberRoles] to an arbitrary JSON value. - * - * You should usually call [Builder.memberRoles] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun memberRoles(memberRoles: JsonField>) = apply { - this.memberRoles = memberRoles.map { it.toMutableList() } - } + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * Adds a single [String] to [memberRoles]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addMemberRole(memberRole: String) = apply { - memberRoles = - (memberRoles ?: JsonField.of(mutableListOf())).also { - checkKnown("memberRoles", it).add(memberRole) - } - } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the role belongs in. - */ - fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ - fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.orgName] to an arbitrary JSON value. - * - * You should usually call [Builder.orgName] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun orgName(orgName: JsonField) = apply { this.orgName = orgName } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("name", name), - description, - (memberPermissions ?: JsonMissing.of()).map { it.toImmutable() }, - (memberRoles ?: JsonMissing.of()).map { it.toImmutable() }, - orgName, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && name == other.name && description == other.description && memberPermissions == other.memberPermissions && memberRoles == other.memberRoles && orgName == other.orgName && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, description, memberPermissions, memberRoles, orgName, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{name=$name, description=$description, memberPermissions=$memberPermissions, memberRoles=$memberRoles, orgName=$orgName, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [RoleReplaceParams]. + * Returns an immutable instance of [RoleReplaceParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java * .name() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): RoleReplaceParams = + RoleReplaceParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [RoleReplaceParams]. */ - @NoAutoDetect - 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(roleReplaceParams: RoleReplaceParams) = apply { - body = roleReplaceParams.body.toBuilder() - additionalHeaders = roleReplaceParams.additionalHeaders.toBuilder() - additionalQueryParams = roleReplaceParams.additionalQueryParams.toBuilder() - } + fun _body(): Body = body - /** Name of the role */ - fun name(name: String) = apply { body.name(name) } + override fun _headers(): Headers = additionalHeaders - /** - * 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 { body.name(name) } + override fun _queryParams(): QueryParams = additionalQueryParams - /** Textual description of the role */ - fun description(description: String?) = apply { body.description(description) } + class Body + private constructor( + private val name: JsonField, + private val description: JsonField, + private val memberPermissions: JsonField>, + private val memberRoles: JsonField>, + private val orgName: JsonField, + private val additionalProperties: MutableMap, + ) { - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("member_permissions") + @ExcludeMissing + memberPermissions: JsonField> = JsonMissing.of(), + @JsonProperty("member_roles") + @ExcludeMissing + memberRoles: JsonField> = JsonMissing.of(), + @JsonProperty("org_name") @ExcludeMissing orgName: JsonField = JsonMissing.of(), + ) : this(name, description, memberPermissions, memberRoles, orgName, mutableMapOf()) /** - * Sets [Builder.description] to an arbitrary JSON value. + * Name of the role * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException 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 description(description: JsonField) = apply { body.description(description) } - - /** (permission, restrict_object_type) tuples which belong to this role */ - fun memberPermissions(memberPermissions: List?) = apply { - body.memberPermissions(memberPermissions) - } - - /** Alias for calling [Builder.memberPermissions] with `memberPermissions.orElse(null)`. */ - fun memberPermissions(memberPermissions: Optional>) = - memberPermissions(memberPermissions.getOrNull()) + fun name(): String = name.getRequired("name") /** - * Sets [Builder.memberPermissions] to an arbitrary JSON value. + * Textual description of the role * - * You should usually call [Builder.memberPermissions] with a well-typed - * `List` value instead. This method is primarily for setting the field to - * an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun memberPermissions(memberPermissions: JsonField>) = apply { - body.memberPermissions(memberPermissions) - } + fun description(): Optional = description.getOptional("description") /** - * Adds a single [MemberPermission] to [memberPermissions]. + * (permission, restrict_object_type) tuples which belong to this role * - * @throws IllegalStateException if the field was previously set to a non-list. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun addMemberPermission(memberPermission: MemberPermission) = apply { - body.addMemberPermission(memberPermission) - } + fun memberPermissions(): Optional> = + memberPermissions.getOptional("member_permissions") /** * Ids of the roles this role inherits from * * An inheriting role has all the permissions contained in its member roles, as well as all * of their inherited permissions + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun memberRoles(memberRoles: List?) = apply { body.memberRoles(memberRoles) } + fun memberRoles(): Optional> = memberRoles.getOptional("member_roles") - /** Alias for calling [Builder.memberRoles] with `memberRoles.orElse(null)`. */ - fun memberRoles(memberRoles: Optional>) = memberRoles(memberRoles.getOrNull()) + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the role belongs in. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun orgName(): Optional = orgName.getOptional("org_name") /** - * Sets [Builder.memberRoles] to an arbitrary JSON value. + * Returns the raw JSON value of [name]. * - * You should usually call [Builder.memberRoles] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. */ - fun memberRoles(memberRoles: JsonField>) = apply { - body.memberRoles(memberRoles) - } + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name /** - * Adds a single [String] to [memberRoles]. + * Returns the raw JSON value of [description]. * - * @throws IllegalStateException if the field was previously set to a non-list. + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. */ - fun addMemberRole(memberRole: String) = apply { body.addMemberRole(memberRole) } + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description /** - * For nearly all users, this parameter should be unnecessary. But in the rare case that - * your API key belongs to multiple organizations, you may specify the name of the - * organization the role belongs in. + * Returns the raw JSON value of [memberPermissions]. + * + * Unlike [memberPermissions], this method doesn't throw if the JSON field has an unexpected + * type. */ - fun orgName(orgName: String?) = apply { body.orgName(orgName) } + @JsonProperty("member_permissions") + @ExcludeMissing + fun _memberPermissions(): JsonField> = memberPermissions - /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ - fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + /** + * Returns the raw JSON value of [memberRoles]. + * + * Unlike [memberRoles], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("member_roles") + @ExcludeMissing + fun _memberRoles(): JsonField> = memberRoles /** - * Sets [Builder.orgName] to an arbitrary JSON value. + * Returns the raw JSON value of [orgName]. * - * You should usually call [Builder.orgName] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. */ - fun orgName(orgName: JsonField) = apply { body.orgName(orgName) } + @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(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 + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var memberPermissions: JsonField>? = null + private var memberRoles: JsonField>? = null + private var orgName: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + description = body.description + memberPermissions = body.memberPermissions.map { it.toMutableList() } + memberRoles = body.memberRoles.map { it.toMutableList() } + orgName = body.orgName + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the role */ + 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 } + + /** Textual description of the role */ + fun description(description: String?) = description(JsonField.ofNullable(description)) + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + + /** (permission, restrict_object_type) tuples which belong to this role */ + fun memberPermissions(memberPermissions: List?) = + memberPermissions(JsonField.ofNullable(memberPermissions)) + + /** + * Alias for calling [Builder.memberPermissions] with `memberPermissions.orElse(null)`. + */ + fun memberPermissions(memberPermissions: Optional>) = + memberPermissions(memberPermissions.getOrNull()) + + /** + * Sets [Builder.memberPermissions] to an arbitrary JSON value. + * + * You should usually call [Builder.memberPermissions] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun memberPermissions(memberPermissions: JsonField>) = apply { + this.memberPermissions = memberPermissions.map { it.toMutableList() } } - 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) - } + /** + * Adds a single [MemberPermission] to [memberPermissions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMemberPermission(memberPermission: MemberPermission) = apply { + memberPermissions = + (memberPermissions ?: JsonField.of(mutableListOf())).also { + checkKnown("memberPermissions", it).add(memberPermission) + } + } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Ids of the roles this role inherits from + * + * An inheriting role has all the permissions contained in its member roles, as well as + * all of their inherited permissions + */ + fun memberRoles(memberRoles: List?) = + memberRoles(JsonField.ofNullable(memberRoles)) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** Alias for calling [Builder.memberRoles] with `memberRoles.orElse(null)`. */ + fun memberRoles(memberRoles: Optional>) = + memberRoles(memberRoles.getOrNull()) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * Sets [Builder.memberRoles] to an arbitrary JSON value. + * + * You should usually call [Builder.memberRoles] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun memberRoles(memberRoles: JsonField>) = apply { + this.memberRoles = memberRoles.map { it.toMutableList() } + } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Adds a single [String] to [memberRoles]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMemberRole(memberRole: String) = apply { + memberRoles = + (memberRoles ?: JsonField.of(mutableListOf())).also { + checkKnown("memberRoles", it).add(memberRole) + } + } - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * For nearly all users, this parameter should be unnecessary. But in the rare case that + * your API key belongs to multiple organizations, you may specify the name of the + * organization the role belongs in. + */ + fun orgName(orgName: String?) = orgName(JsonField.ofNullable(orgName)) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** + * Sets [Builder.orgName] to an arbitrary JSON value. + * + * You should usually call [Builder.orgName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun orgName(orgName: JsonField) = apply { this.orgName = orgName } - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("name", name), + description, + (memberPermissions ?: JsonMissing.of()).map { it.toImmutable() }, + (memberRoles ?: JsonMissing.of()).map { it.toImmutable() }, + orgName, + additionalProperties.toMutableMap(), + ) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + private var validated: Boolean = false - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun validate(): Body = apply { + if (validated) { + return@apply + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) + name() + description() + memberPermissions().ifPresent { it.forEach { it.validate() } } + memberRoles() + orgName() + validated = true } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (memberPermissions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (memberRoles.asKnown().getOrNull()?.size ?: 0) + + (if (orgName.asKnown().isPresent) 1 else 0) - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + return /* spotless:off */ other is Body && name == other.name && description == other.description && memberPermissions == other.memberPermissions && memberRoles == other.memberRoles && orgName == other.orgName && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, description, memberPermissions, memberRoles, orgName, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [RoleReplaceParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): RoleReplaceParams = - RoleReplaceParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{name=$name, description=$description, memberPermissions=$memberPermissions, memberRoles=$memberRoles, orgName=$orgName, additionalProperties=$additionalProperties}" } - @NoAutoDetect class MemberPermission - @JsonCreator private constructor( - @JsonProperty("permission") - @ExcludeMissing - private val permission: JsonField = JsonMissing.of(), - @JsonProperty("restrict_object_type") - @ExcludeMissing - private val restrictObjectType: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val permission: JsonField, + private val restrictObjectType: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("permission") + @ExcludeMissing + permission: JsonField = JsonMissing.of(), + @JsonProperty("restrict_object_type") + @ExcludeMissing + restrictObjectType: JsonField = JsonMissing.of(), + ) : this(permission, restrictObjectType, mutableMapOf()) + /** * Each permission permits a certain type of operation on an object in the system * @@ -771,7 +814,7 @@ private constructor( * the server responded with an unexpected value). */ fun restrictObjectType(): Optional = - Optional.ofNullable(restrictObjectType.getNullable("restrict_object_type")) + restrictObjectType.getOptional("restrict_object_type") /** * Returns the raw JSON value of [permission]. @@ -792,21 +835,15 @@ private constructor( @ExcludeMissing fun _restrictObjectType(): JsonField = restrictObjectType + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): MemberPermission = apply { - if (validated) { - return@apply - } - - permission() - restrictObjectType() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -913,10 +950,41 @@ private constructor( MemberPermission( checkRequired("permission", permission), restrictObjectType, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): MemberPermission = apply { + if (validated) { + return@apply + } + + permission().validate() + restrictObjectType().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (permission.asKnown().getOrNull()?.validity() ?: 0) + + (restrictObjectType.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleRetrieveParams.kt index 1afba4b5..2b82d6ea 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> roleId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [RoleRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var roleId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> roleId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleUpdateParams.kt index da629d22..390da928 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleUpdateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleUpdateParams.kt @@ -6,19 +6,18 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkKnown import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -140,186 +139,524 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) - override fun _headers(): Headers = additionalHeaders + companion object { - override fun _queryParams(): QueryParams = additionalQueryParams + /** + * Returns a mutable builder for constructing an instance of [RoleUpdateParams]. + * + * The following fields are required: + * ```java + * .roleId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - fun getPathParam(index: Int): String { - return when (index) { - 0 -> roleId - else -> "" + /** A builder for [RoleUpdateParams]. */ + class Builder internal constructor() { + + private var roleId: 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(roleUpdateParams: RoleUpdateParams) = apply { + roleId = roleUpdateParams.roleId + body = roleUpdateParams.body.toBuilder() + additionalHeaders = roleUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = roleUpdateParams.additionalQueryParams.toBuilder() } - } - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("add_member_permissions") - @ExcludeMissing - private val addMemberPermissions: JsonField> = JsonMissing.of(), - @JsonProperty("add_member_roles") - @ExcludeMissing - private val addMemberRoles: JsonField> = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("remove_member_permissions") - @ExcludeMissing - private val removeMemberPermissions: JsonField> = - JsonMissing.of(), - @JsonProperty("remove_member_roles") - @ExcludeMissing - private val removeMemberRoles: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** Role id */ + fun roleId(roleId: String) = apply { this.roleId = roleId } /** - * A list of permissions to add to the role + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [addMemberPermissions] + * - [addMemberRoles] + * - [description] + * - [name] + * - [removeMemberPermissions] + * - etc. */ - fun addMemberPermissions(): Optional> = - Optional.ofNullable(addMemberPermissions.getNullable("add_member_permissions")) + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** A list of permissions to add to the role */ + fun addMemberPermissions(addMemberPermissions: List?) = apply { + body.addMemberPermissions(addMemberPermissions) + } /** - * A list of role IDs to add to the role's inheriting-from set - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * Alias for calling [Builder.addMemberPermissions] with + * `addMemberPermissions.orElse(null)`. */ - fun addMemberRoles(): Optional> = - Optional.ofNullable(addMemberRoles.getNullable("add_member_roles")) + fun addMemberPermissions(addMemberPermissions: Optional>) = + addMemberPermissions(addMemberPermissions.getOrNull()) /** - * Textual description of the role + * Sets [Builder.addMemberPermissions] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.addMemberPermissions] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun addMemberPermissions(addMemberPermissions: JsonField>) = + apply { + body.addMemberPermissions(addMemberPermissions) + } /** - * Name of the role + * Adds a single [AddMemberPermission] to [addMemberPermissions]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * @throws IllegalStateException if the field was previously set to a non-list. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun addAddMemberPermission(addMemberPermission: AddMemberPermission) = apply { + body.addAddMemberPermission(addMemberPermission) + } + + /** A list of role IDs to add to the role's inheriting-from set */ + fun addMemberRoles(addMemberRoles: List?) = apply { + body.addMemberRoles(addMemberRoles) + } + + /** Alias for calling [Builder.addMemberRoles] with `addMemberRoles.orElse(null)`. */ + fun addMemberRoles(addMemberRoles: Optional>) = + addMemberRoles(addMemberRoles.getOrNull()) /** - * A list of permissions to remove from the role + * Sets [Builder.addMemberRoles] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.addMemberRoles] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun removeMemberPermissions(): Optional> = - Optional.ofNullable(removeMemberPermissions.getNullable("remove_member_permissions")) + fun addMemberRoles(addMemberRoles: JsonField>) = apply { + body.addMemberRoles(addMemberRoles) + } /** - * A list of role IDs to remove from the role's inheriting-from set + * Adds a single [String] to [addMemberRoles]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * @throws IllegalStateException if the field was previously set to a non-list. */ - fun removeMemberRoles(): Optional> = - Optional.ofNullable(removeMemberRoles.getNullable("remove_member_roles")) + fun addAddMemberRole(addMemberRole: String) = apply { body.addAddMemberRole(addMemberRole) } + + /** Textual description of the role */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) /** - * Returns the raw JSON value of [addMemberPermissions]. + * Sets [Builder.description] to an arbitrary JSON value. * - * Unlike [addMemberPermissions], this method doesn't throw if the JSON field has an - * unexpected type. + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("add_member_permissions") - @ExcludeMissing - fun _addMemberPermissions(): JsonField> = addMemberPermissions + fun description(description: JsonField) = apply { body.description(description) } + + /** Name of the role */ + fun name(name: String?) = apply { body.name(name) } + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) /** - * Returns the raw JSON value of [addMemberRoles]. + * Sets [Builder.name] to an arbitrary JSON value. * - * Unlike [addMemberRoles], this method doesn't throw if the JSON field has an unexpected - * type. + * 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. */ - @JsonProperty("add_member_roles") - @ExcludeMissing - fun _addMemberRoles(): JsonField> = addMemberRoles + fun name(name: JsonField) = apply { body.name(name) } + + /** A list of permissions to remove from the role */ + fun removeMemberPermissions(removeMemberPermissions: List?) = + apply { + body.removeMemberPermissions(removeMemberPermissions) + } /** - * Returns the raw JSON value of [description]. + * Alias for calling [Builder.removeMemberPermissions] with + * `removeMemberPermissions.orElse(null)`. + */ + fun removeMemberPermissions( + removeMemberPermissions: Optional> + ) = removeMemberPermissions(removeMemberPermissions.getOrNull()) + + /** + * Sets [Builder.removeMemberPermissions] to an arbitrary JSON value. * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.removeMemberPermissions] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description + fun removeMemberPermissions( + removeMemberPermissions: JsonField> + ) = apply { body.removeMemberPermissions(removeMemberPermissions) } /** - * Returns the raw JSON value of [name]. + * Adds a single [RemoveMemberPermission] to [removeMemberPermissions]. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun addRemoveMemberPermission(removeMemberPermission: RemoveMemberPermission) = apply { + body.addRemoveMemberPermission(removeMemberPermission) + } + + /** A list of role IDs to remove from the role's inheriting-from set */ + fun removeMemberRoles(removeMemberRoles: List?) = apply { + body.removeMemberRoles(removeMemberRoles) + } + + /** Alias for calling [Builder.removeMemberRoles] with `removeMemberRoles.orElse(null)`. */ + fun removeMemberRoles(removeMemberRoles: Optional>) = + removeMemberRoles(removeMemberRoles.getOrNull()) /** - * Returns the raw JSON value of [removeMemberPermissions]. + * Sets [Builder.removeMemberRoles] to an arbitrary JSON value. * - * Unlike [removeMemberPermissions], this method doesn't throw if the JSON field has an - * unexpected type. + * You should usually call [Builder.removeMemberRoles] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. */ - @JsonProperty("remove_member_permissions") - @ExcludeMissing - fun _removeMemberPermissions(): JsonField> = - removeMemberPermissions + fun removeMemberRoles(removeMemberRoles: JsonField>) = apply { + body.removeMemberRoles(removeMemberRoles) + } /** - * Returns the raw JSON value of [removeMemberRoles]. + * Adds a single [String] to [removeMemberRoles]. * - * Unlike [removeMemberRoles], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("remove_member_roles") - @ExcludeMissing - fun _removeMemberRoles(): JsonField> = removeMemberRoles + fun addRemoveMemberRole(removeMemberRole: String) = apply { + body.addRemoveMemberRole(removeMemberRole) + } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var validated: Boolean = false + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - fun validate(): Body = apply { - if (validated) { - return@apply + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - addMemberPermissions().ifPresent { it.forEach { it.validate() } } - addMemberRoles() - description() - name() - removeMemberPermissions().ifPresent { it.forEach { it.validate() } } - removeMemberRoles() - validated = true - } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun toBuilder() = Builder().from(this) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - companion object { + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Returns a mutable builder for constructing an instance of [Body]. */ - @JvmStatic fun builder() = Builder() + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - /** A builder for [Body]. */ - class Builder internal constructor() { + 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 [RoleUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .roleId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RoleUpdateParams = + RoleUpdateParams( + checkRequired("roleId", roleId), + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> roleId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val addMemberPermissions: JsonField>, + private val addMemberRoles: JsonField>, + private val description: JsonField, + private val name: JsonField, + private val removeMemberPermissions: JsonField>, + private val removeMemberRoles: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("add_member_permissions") + @ExcludeMissing + addMemberPermissions: JsonField> = JsonMissing.of(), + @JsonProperty("add_member_roles") + @ExcludeMissing + addMemberRoles: JsonField> = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("remove_member_permissions") + @ExcludeMissing + removeMemberPermissions: JsonField> = JsonMissing.of(), + @JsonProperty("remove_member_roles") + @ExcludeMissing + removeMemberRoles: JsonField> = JsonMissing.of(), + ) : this( + addMemberPermissions, + addMemberRoles, + description, + name, + removeMemberPermissions, + removeMemberRoles, + mutableMapOf(), + ) + + /** + * A list of permissions to add to the role + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun addMemberPermissions(): Optional> = + addMemberPermissions.getOptional("add_member_permissions") + + /** + * A list of role IDs to add to the role's inheriting-from set + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun addMemberRoles(): Optional> = + addMemberRoles.getOptional("add_member_roles") + + /** + * Textual description of the role + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * Name of the role + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * A list of permissions to remove from the role + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun removeMemberPermissions(): Optional> = + removeMemberPermissions.getOptional("remove_member_permissions") + + /** + * A list of role IDs to remove from the role's inheriting-from set + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun removeMemberRoles(): Optional> = + removeMemberRoles.getOptional("remove_member_roles") + + /** + * Returns the raw JSON value of [addMemberPermissions]. + * + * Unlike [addMemberPermissions], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("add_member_permissions") + @ExcludeMissing + fun _addMemberPermissions(): JsonField> = addMemberPermissions + + /** + * Returns the raw JSON value of [addMemberRoles]. + * + * Unlike [addMemberRoles], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("add_member_roles") + @ExcludeMissing + fun _addMemberRoles(): JsonField> = addMemberRoles + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [removeMemberPermissions]. + * + * Unlike [removeMemberPermissions], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("remove_member_permissions") + @ExcludeMissing + fun _removeMemberPermissions(): JsonField> = + removeMemberPermissions + + /** + * Returns the raw JSON value of [removeMemberRoles]. + * + * Unlike [removeMemberRoles], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("remove_member_roles") + @ExcludeMissing + fun _removeMemberRoles(): JsonField> = removeMemberRoles + + @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]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { private var addMemberPermissions: JsonField>? = null private var addMemberRoles: JsonField>? = null @@ -449,459 +786,177 @@ private constructor( */ fun removeMemberPermissions( removeMemberPermissions: Optional> - ) = removeMemberPermissions(removeMemberPermissions.getOrNull()) - - /** - * Sets [Builder.removeMemberPermissions] to an arbitrary JSON value. - * - * You should usually call [Builder.removeMemberPermissions] with a well-typed - * `List` value instead. This method is primarily for setting - * the field to an undocumented or not yet supported value. - */ - fun removeMemberPermissions( - removeMemberPermissions: JsonField> - ) = apply { - this.removeMemberPermissions = removeMemberPermissions.map { it.toMutableList() } - } - - /** - * Adds a single [RemoveMemberPermission] to [removeMemberPermissions]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addRemoveMemberPermission(removeMemberPermission: RemoveMemberPermission) = apply { - removeMemberPermissions = - (removeMemberPermissions ?: JsonField.of(mutableListOf())).also { - checkKnown("removeMemberPermissions", it).add(removeMemberPermission) - } - } - - /** A list of role IDs to remove from the role's inheriting-from set */ - fun removeMemberRoles(removeMemberRoles: List?) = - removeMemberRoles(JsonField.ofNullable(removeMemberRoles)) - - /** - * Alias for calling [Builder.removeMemberRoles] with `removeMemberRoles.orElse(null)`. - */ - fun removeMemberRoles(removeMemberRoles: Optional>) = - removeMemberRoles(removeMemberRoles.getOrNull()) - - /** - * Sets [Builder.removeMemberRoles] to an arbitrary JSON value. - * - * You should usually call [Builder.removeMemberRoles] with a well-typed `List` - * value instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun removeMemberRoles(removeMemberRoles: JsonField>) = apply { - this.removeMemberRoles = removeMemberRoles.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [removeMemberRoles]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addRemoveMemberRole(removeMemberRole: String) = apply { - removeMemberRoles = - (removeMemberRoles ?: JsonField.of(mutableListOf())).also { - checkKnown("removeMemberRoles", it).add(removeMemberRole) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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. - */ - fun build(): Body = - Body( - (addMemberPermissions ?: JsonMissing.of()).map { it.toImmutable() }, - (addMemberRoles ?: JsonMissing.of()).map { it.toImmutable() }, - description, - name, - (removeMemberPermissions ?: JsonMissing.of()).map { it.toImmutable() }, - (removeMemberRoles ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && addMemberPermissions == other.addMemberPermissions && addMemberRoles == other.addMemberRoles && description == other.description && name == other.name && removeMemberPermissions == other.removeMemberPermissions && removeMemberRoles == other.removeMemberRoles && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(addMemberPermissions, addMemberRoles, description, name, removeMemberPermissions, removeMemberRoles, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{addMemberPermissions=$addMemberPermissions, addMemberRoles=$addMemberRoles, description=$description, name=$name, removeMemberPermissions=$removeMemberPermissions, removeMemberRoles=$removeMemberRoles, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [RoleUpdateParams]. - * - * The following fields are required: - * ```java - * .roleId() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [RoleUpdateParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var roleId: 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(roleUpdateParams: RoleUpdateParams) = apply { - roleId = roleUpdateParams.roleId - body = roleUpdateParams.body.toBuilder() - additionalHeaders = roleUpdateParams.additionalHeaders.toBuilder() - additionalQueryParams = roleUpdateParams.additionalQueryParams.toBuilder() - } - - /** Role id */ - fun roleId(roleId: String) = apply { this.roleId = roleId } - - /** A list of permissions to add to the role */ - fun addMemberPermissions(addMemberPermissions: List?) = apply { - body.addMemberPermissions(addMemberPermissions) - } - - /** - * Alias for calling [Builder.addMemberPermissions] with - * `addMemberPermissions.orElse(null)`. - */ - fun addMemberPermissions(addMemberPermissions: Optional>) = - addMemberPermissions(addMemberPermissions.getOrNull()) - - /** - * Sets [Builder.addMemberPermissions] to an arbitrary JSON value. - * - * You should usually call [Builder.addMemberPermissions] with a well-typed - * `List` value instead. This method is primarily for setting the field - * to an undocumented or not yet supported value. - */ - fun addMemberPermissions(addMemberPermissions: JsonField>) = - apply { - body.addMemberPermissions(addMemberPermissions) - } - - /** - * Adds a single [AddMemberPermission] to [addMemberPermissions]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addAddMemberPermission(addMemberPermission: AddMemberPermission) = apply { - body.addAddMemberPermission(addMemberPermission) - } - - /** A list of role IDs to add to the role's inheriting-from set */ - fun addMemberRoles(addMemberRoles: List?) = apply { - body.addMemberRoles(addMemberRoles) - } - - /** Alias for calling [Builder.addMemberRoles] with `addMemberRoles.orElse(null)`. */ - fun addMemberRoles(addMemberRoles: Optional>) = - addMemberRoles(addMemberRoles.getOrNull()) - - /** - * Sets [Builder.addMemberRoles] to an arbitrary JSON value. - * - * You should usually call [Builder.addMemberRoles] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun addMemberRoles(addMemberRoles: JsonField>) = apply { - body.addMemberRoles(addMemberRoles) - } - - /** - * Adds a single [String] to [addMemberRoles]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addAddMemberRole(addMemberRole: String) = apply { body.addAddMemberRole(addMemberRole) } - - /** Textual description of the role */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun description(description: JsonField) = apply { body.description(description) } - - /** Name of the role */ - fun name(name: String?) = apply { body.name(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 { body.name(name) } - - /** A list of permissions to remove from the role */ - fun removeMemberPermissions(removeMemberPermissions: List?) = - apply { - body.removeMemberPermissions(removeMemberPermissions) - } - - /** - * Alias for calling [Builder.removeMemberPermissions] with - * `removeMemberPermissions.orElse(null)`. - */ - fun removeMemberPermissions( - removeMemberPermissions: Optional> - ) = removeMemberPermissions(removeMemberPermissions.getOrNull()) - - /** - * Sets [Builder.removeMemberPermissions] to an arbitrary JSON value. - * - * You should usually call [Builder.removeMemberPermissions] with a well-typed - * `List` value instead. This method is primarily for setting the - * field to an undocumented or not yet supported value. - */ - fun removeMemberPermissions( - removeMemberPermissions: JsonField> - ) = apply { body.removeMemberPermissions(removeMemberPermissions) } - - /** - * Adds a single [RemoveMemberPermission] to [removeMemberPermissions]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addRemoveMemberPermission(removeMemberPermission: RemoveMemberPermission) = apply { - body.addRemoveMemberPermission(removeMemberPermission) - } - - /** A list of role IDs to remove from the role's inheriting-from set */ - fun removeMemberRoles(removeMemberRoles: List?) = apply { - body.removeMemberRoles(removeMemberRoles) - } - - /** Alias for calling [Builder.removeMemberRoles] with `removeMemberRoles.orElse(null)`. */ - fun removeMemberRoles(removeMemberRoles: Optional>) = - removeMemberRoles(removeMemberRoles.getOrNull()) - - /** - * Sets [Builder.removeMemberRoles] to an arbitrary JSON value. - * - * You should usually call [Builder.removeMemberRoles] with a well-typed `List` - * value instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun removeMemberRoles(removeMemberRoles: JsonField>) = apply { - body.removeMemberRoles(removeMemberRoles) - } - - /** - * Adds a single [String] to [removeMemberRoles]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addRemoveMemberRole(removeMemberRole: String) = apply { - body.addRemoveMemberRole(removeMemberRole) - } - - 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) - } + ) = removeMemberPermissions(removeMemberPermissions.getOrNull()) - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Sets [Builder.removeMemberPermissions] to an arbitrary JSON value. + * + * You should usually call [Builder.removeMemberPermissions] with a well-typed + * `List` value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun removeMemberPermissions( + removeMemberPermissions: JsonField> + ) = apply { + this.removeMemberPermissions = removeMemberPermissions.map { it.toMutableList() } + } - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Adds a single [RemoveMemberPermission] to [removeMemberPermissions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addRemoveMemberPermission(removeMemberPermission: RemoveMemberPermission) = apply { + removeMemberPermissions = + (removeMemberPermissions ?: JsonField.of(mutableListOf())).also { + checkKnown("removeMemberPermissions", it).add(removeMemberPermission) + } + } - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** A list of role IDs to remove from the role's inheriting-from set */ + fun removeMemberRoles(removeMemberRoles: List?) = + removeMemberRoles(JsonField.ofNullable(removeMemberRoles)) - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** + * Alias for calling [Builder.removeMemberRoles] with `removeMemberRoles.orElse(null)`. + */ + fun removeMemberRoles(removeMemberRoles: Optional>) = + removeMemberRoles(removeMemberRoles.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.removeMemberRoles] to an arbitrary JSON value. + * + * You should usually call [Builder.removeMemberRoles] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun removeMemberRoles(removeMemberRoles: JsonField>) = apply { + this.removeMemberRoles = removeMemberRoles.map { it.toMutableList() } + } - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Adds a single [String] to [removeMemberRoles]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addRemoveMemberRole(removeMemberRole: String) = apply { + removeMemberRoles = + (removeMemberRoles ?: JsonField.of(mutableListOf())).also { + checkKnown("removeMemberRoles", it).add(removeMemberRole) + } + } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body( + (addMemberPermissions ?: JsonMissing.of()).map { it.toImmutable() }, + (addMemberRoles ?: JsonMissing.of()).map { it.toImmutable() }, + description, + name, + (removeMemberPermissions ?: JsonMissing.of()).map { it.toImmutable() }, + (removeMemberRoles ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + private var validated: Boolean = false - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun validate(): Body = apply { + if (validated) { + return@apply } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) + addMemberPermissions().ifPresent { it.forEach { it.validate() } } + addMemberRoles() + description() + name() + removeMemberPermissions().ifPresent { it.forEach { it.validate() } } + removeMemberRoles() + validated = true } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (addMemberPermissions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (addMemberRoles.asKnown().getOrNull()?.size ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (removeMemberPermissions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } + ?: 0) + + (removeMemberRoles.asKnown().getOrNull()?.size ?: 0) - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + return /* spotless:off */ other is Body && addMemberPermissions == other.addMemberPermissions && addMemberRoles == other.addMemberRoles && description == other.description && name == other.name && removeMemberPermissions == other.removeMemberPermissions && removeMemberRoles == other.removeMemberRoles && additionalProperties == other.additionalProperties /* spotless:on */ } - /** - * Returns an immutable instance of [RoleUpdateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .roleId() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): RoleUpdateParams = - RoleUpdateParams( - checkRequired("roleId", roleId), - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(addMemberPermissions, addMemberRoles, description, name, removeMemberPermissions, removeMemberRoles, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{addMemberPermissions=$addMemberPermissions, addMemberRoles=$addMemberRoles, description=$description, name=$name, removeMemberPermissions=$removeMemberPermissions, removeMemberRoles=$removeMemberRoles, additionalProperties=$additionalProperties}" } - @NoAutoDetect class AddMemberPermission - @JsonCreator private constructor( - @JsonProperty("permission") - @ExcludeMissing - private val permission: JsonField = JsonMissing.of(), - @JsonProperty("restrict_object_type") - @ExcludeMissing - private val restrictObjectType: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val permission: JsonField, + private val restrictObjectType: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("permission") + @ExcludeMissing + permission: JsonField = JsonMissing.of(), + @JsonProperty("restrict_object_type") + @ExcludeMissing + restrictObjectType: JsonField = JsonMissing.of(), + ) : this(permission, restrictObjectType, mutableMapOf()) + /** * Each permission permits a certain type of operation on an object in the system * @@ -919,7 +974,7 @@ private constructor( * the server responded with an unexpected value). */ fun restrictObjectType(): Optional = - Optional.ofNullable(restrictObjectType.getNullable("restrict_object_type")) + restrictObjectType.getOptional("restrict_object_type") /** * Returns the raw JSON value of [permission]. @@ -940,21 +995,15 @@ private constructor( @ExcludeMissing fun _restrictObjectType(): JsonField = restrictObjectType + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AddMemberPermission = apply { - if (validated) { - return@apply - } - - permission() - restrictObjectType() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1061,10 +1110,41 @@ private constructor( AddMemberPermission( checkRequired("permission", permission), restrictObjectType, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): AddMemberPermission = apply { + if (validated) { + return@apply + } + + permission().validate() + restrictObjectType().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (permission.asKnown().getOrNull()?.validity() ?: 0) + + (restrictObjectType.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1083,20 +1163,23 @@ private constructor( "AddMemberPermission{permission=$permission, restrictObjectType=$restrictObjectType, additionalProperties=$additionalProperties}" } - @NoAutoDetect class RemoveMemberPermission - @JsonCreator private constructor( - @JsonProperty("permission") - @ExcludeMissing - private val permission: JsonField = JsonMissing.of(), - @JsonProperty("restrict_object_type") - @ExcludeMissing - private val restrictObjectType: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val permission: JsonField, + private val restrictObjectType: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("permission") + @ExcludeMissing + permission: JsonField = JsonMissing.of(), + @JsonProperty("restrict_object_type") + @ExcludeMissing + restrictObjectType: JsonField = JsonMissing.of(), + ) : this(permission, restrictObjectType, mutableMapOf()) + /** * Each permission permits a certain type of operation on an object in the system * @@ -1114,7 +1197,7 @@ private constructor( * the server responded with an unexpected value). */ fun restrictObjectType(): Optional = - Optional.ofNullable(restrictObjectType.getNullable("restrict_object_type")) + restrictObjectType.getOptional("restrict_object_type") /** * Returns the raw JSON value of [permission]. @@ -1135,21 +1218,15 @@ private constructor( @ExcludeMissing fun _restrictObjectType(): JsonField = restrictObjectType + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): RemoveMemberPermission = apply { - if (validated) { - return@apply - } - - permission() - restrictObjectType() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -1256,10 +1333,41 @@ private constructor( RemoveMemberPermission( checkRequired("permission", permission), restrictObjectType, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): RemoveMemberPermission = apply { + if (validated) { + return@apply + } + + permission().validate() + restrictObjectType().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (permission.asKnown().getOrNull()?.validity() ?: 0) + + (restrictObjectType.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ScoreSummary.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ScoreSummary.kt index 2d7c5189..207b7123 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ScoreSummary.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ScoreSummary.kt @@ -6,35 +6,40 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 /** Summary of a score's performance */ -@NoAutoDetect class ScoreSummary -@JsonCreator private constructor( - @JsonProperty("improvements") - @ExcludeMissing - private val improvements: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("regressions") - @ExcludeMissing - private val regressions: JsonField = JsonMissing.of(), - @JsonProperty("score") @ExcludeMissing private val score: JsonField = JsonMissing.of(), - @JsonProperty("diff") @ExcludeMissing private val diff: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val improvements: JsonField, + private val name: JsonField, + private val regressions: JsonField, + private val score: JsonField, + private val diff: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("improvements") + @ExcludeMissing + improvements: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("regressions") + @ExcludeMissing + regressions: JsonField = JsonMissing.of(), + @JsonProperty("score") @ExcludeMissing score: JsonField = JsonMissing.of(), + @JsonProperty("diff") @ExcludeMissing diff: JsonField = JsonMissing.of(), + ) : this(improvements, name, regressions, score, diff, mutableMapOf()) + /** * Number of improvements in the score * @@ -73,7 +78,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun diff(): Optional = Optional.ofNullable(diff.getNullable("diff")) + fun diff(): Optional = diff.getOptional("diff") /** * Returns the raw JSON value of [improvements]. @@ -112,24 +117,15 @@ private constructor( */ @JsonProperty("diff") @ExcludeMissing fun _diff(): JsonField = diff + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ScoreSummary = apply { - if (validated) { - return@apply - } - - improvements() - name() - regressions() - score() - diff() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -267,10 +263,46 @@ private constructor( checkRequired("regressions", regressions), checkRequired("score", score), diff, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): ScoreSummary = apply { + if (validated) { + return@apply + } + + improvements() + name() + regressions() + score() + diff() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (improvements.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (regressions.asKnown().isPresent) 1 else 0) + + (if (score.asKnown().isPresent) 1 else 0) + + (if (diff.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanAttributes.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanAttributes.kt index 68f8d827..13b88570 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanAttributes.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanAttributes.kt @@ -6,35 +6,37 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 /** Human-identifying attributes of the span, such as name, type, etc. */ -@NoAutoDetect class SpanAttributes -@JsonCreator private constructor( - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(name, type, mutableMapOf()) + /** * Name of the span, for display purposes only * * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + fun name(): Optional = name.getOptional("name") /** * Type of the span, for display purposes only @@ -42,7 +44,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + fun type(): Optional = type.getOptional("type") /** * Returns the raw JSON value of [name]. @@ -58,21 +60,15 @@ private constructor( */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SpanAttributes = apply { - if (validated) { - return@apply - } - - name() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -148,9 +144,39 @@ private constructor( * * Further updates to this [Builder] will not mutate the returned instance. */ - fun build(): SpanAttributes = SpanAttributes(name, type, additionalProperties.toImmutable()) + fun build(): SpanAttributes = + SpanAttributes(name, type, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): SpanAttributes = apply { + if (validated) { + return@apply + } + + name() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + (type.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIFrame.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIFrame.kt index bd4d2359..65ede1b3 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIFrame.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIFrame.kt @@ -6,48 +6,64 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class SpanIFrame -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing private val url: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("deleted_at") - @ExcludeMissing - private val deletedAt: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("post_message") - @ExcludeMissing - private val postMessage: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val name: JsonField, + private val projectId: JsonField, + private val url: JsonField, + private val created: JsonField, + private val deletedAt: JsonField, + private val description: JsonField, + private val postMessage: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") @ExcludeMissing projectId: JsonField = JsonMissing.of(), + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("deleted_at") + @ExcludeMissing + deletedAt: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("post_message") + @ExcludeMissing + postMessage: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this( + id, + name, + projectId, + url, + created, + deletedAt, + description, + postMessage, + userId, + mutableMapOf(), + ) + /** * Unique identifier for the span iframe * @@ -86,7 +102,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Date of span iframe deletion, or null if the span iframe is still active @@ -94,8 +110,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun deletedAt(): Optional = - Optional.ofNullable(deletedAt.getNullable("deleted_at")) + fun deletedAt(): Optional = deletedAt.getOptional("deleted_at") /** * Textual description of the span iframe @@ -103,8 +118,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun description(): Optional = description.getOptional("description") /** * Whether to post messages to the iframe containing the span's data. This is useful when you @@ -113,8 +127,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun postMessage(): Optional = - Optional.ofNullable(postMessage.getNullable("post_message")) + fun postMessage(): Optional = postMessage.getOptional("post_message") /** * Identifies the user who created the span iframe @@ -122,7 +135,7 @@ private constructor( * @throws BraintrustInvalidDataException 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 [id]. @@ -191,28 +204,15 @@ private constructor( */ @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 = additionalProperties - - private var validated: Boolean = false - - fun validate(): SpanIFrame = apply { - if (validated) { - return@apply - } - - id() - name() - projectId() - url() - created() - deletedAt() - description() - postMessage() - userId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -434,10 +434,54 @@ private constructor( description, postMessage, userId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): SpanIFrame = apply { + if (validated) { + return@apply + } + + id() + name() + projectId() + url() + created() + deletedAt() + description() + postMessage() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (url.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (deletedAt.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (postMessage.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeCreateParams.kt index 6883efec..8d2e050d 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeCreateParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -115,33 +113,295 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [SpanIframeCreateParams]. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SpanIframeCreateParams]. */ + 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(spanIframeCreateParams: SpanIframeCreateParams) = apply { + body = spanIframeCreateParams.body.toBuilder() + additionalHeaders = spanIframeCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = spanIframeCreateParams.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: + * - [name] + * - [projectId] + * - [url] + * - [description] + * - [postMessage] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the span iframe */ + fun name(name: String) = apply { body.name(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 { body.name(name) } + + /** Unique identifier for the project that the span iframe belongs under */ + fun projectId(projectId: String) = apply { body.projectId(projectId) } + + /** + * Sets [Builder.projectId] to an arbitrary JSON value. + * + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } + + /** URL to embed the project viewer in an iframe */ + fun url(url: String) = apply { body.url(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 { body.url(url) } + + /** Textual description of the span iframe */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { body.description(description) } + + /** + * Whether to post messages to the iframe containing the span's data. This is useful when + * you want to render more data than fits in the URL. + */ + fun postMessage(postMessage: Boolean?) = apply { body.postMessage(postMessage) } + + /** + * Alias for [Builder.postMessage]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun postMessage(postMessage: Boolean) = postMessage(postMessage as Boolean?) + + /** Alias for calling [Builder.postMessage] with `postMessage.orElse(null)`. */ + fun postMessage(postMessage: Optional) = postMessage(postMessage.getOrNull()) + + /** + * Sets [Builder.postMessage] to an arbitrary JSON value. + * + * You should usually call [Builder.postMessage] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun postMessage(postMessage: JsonField) = apply { body.postMessage(postMessage) } + + 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 [SpanIframeCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SpanIframeCreateParams = + SpanIframeCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body override fun _headers(): Headers = additionalHeaders override fun _queryParams(): QueryParams = additionalQueryParams - @NoAutoDetect class Body - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing private val url: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("post_message") - @ExcludeMissing - private val postMessage: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val projectId: JsonField, + private val url: JsonField, + private val description: JsonField, + private val postMessage: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") + @ExcludeMissing + projectId: JsonField = JsonMissing.of(), + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("post_message") + @ExcludeMissing + postMessage: JsonField = JsonMissing.of(), + ) : this(name, projectId, url, description, postMessage, mutableMapOf()) + /** * Name of the span iframe * @@ -172,8 +432,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun description(): Optional = description.getOptional("description") /** * Whether to post messages to the iframe containing the span's data. This is useful when @@ -182,8 +441,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun postMessage(): Optional = - Optional.ofNullable(postMessage.getNullable("post_message")) + fun postMessage(): Optional = postMessage.getOptional("post_message") /** * Returns the raw JSON value of [name]. @@ -224,24 +482,15 @@ private constructor( @ExcludeMissing fun _postMessage(): JsonField = postMessage + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - name() - projectId() - url() - description() - postMessage() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -400,271 +649,63 @@ private constructor( checkRequired("url", url), description, postMessage, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply } - return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && url == other.url && description == other.description && postMessage == other.postMessage && additionalProperties == other.additionalProperties /* spotless:on */ + name() + projectId() + url() + description() + postMessage() + validated = true } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, projectId, url, description, postMessage, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{name=$name, projectId=$projectId, url=$url, description=$description, postMessage=$postMessage, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } /** - * Returns a mutable builder for constructing an instance of [SpanIframeCreateParams]. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .url() - * ``` + * Used for best match union deserialization. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [SpanIframeCreateParams]. */ - @NoAutoDetect - 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(spanIframeCreateParams: SpanIframeCreateParams) = apply { - body = spanIframeCreateParams.body.toBuilder() - additionalHeaders = spanIframeCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = spanIframeCreateParams.additionalQueryParams.toBuilder() - } - - /** Name of the span iframe */ - fun name(name: String) = apply { body.name(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 { body.name(name) } - - /** Unique identifier for the project that the span iframe belongs under */ - fun projectId(projectId: String) = apply { body.projectId(projectId) } - - /** - * Sets [Builder.projectId] to an arbitrary JSON value. - * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } - - /** URL to embed the project viewer in an iframe */ - fun url(url: String) = apply { body.url(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 { body.url(url) } - - /** Textual description of the span iframe */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun description(description: JsonField) = apply { body.description(description) } - - /** - * Whether to post messages to the iframe containing the span's data. This is useful when - * you want to render more data than fits in the URL. - */ - fun postMessage(postMessage: Boolean?) = apply { body.postMessage(postMessage) } - - /** - * Alias for [Builder.postMessage]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun postMessage(postMessage: Boolean) = postMessage(postMessage as Boolean?) - - /** Alias for calling [Builder.postMessage] with `postMessage.orElse(null)`. */ - fun postMessage(postMessage: Optional) = postMessage(postMessage.getOrNull()) - - /** - * Sets [Builder.postMessage] to an arbitrary JSON value. - * - * You should usually call [Builder.postMessage] with a well-typed [Boolean] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun postMessage(postMessage: JsonField) = apply { body.postMessage(postMessage) } - - 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) - } + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (url.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (postMessage.asKnown().isPresent) 1 else 0) - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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) + return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && url == other.url && description == other.description && postMessage == other.postMessage && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, projectId, url, description, postMessage, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [SpanIframeCreateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .url() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): SpanIframeCreateParams = - SpanIframeCreateParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{name=$name, projectId=$projectId, url=$url, description=$description, postMessage=$postMessage, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeDeleteParams.kt index da0b2c4a..cf73c830 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeDeleteParams.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,26 +23,11 @@ private constructor( /** SpanIframe id */ fun spanIframeId(): String = spanIframeId - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> spanIframeId - else -> "" - } - } + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -61,7 +45,6 @@ private constructor( } /** A builder for [SpanIframeDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var spanIframeId: String? = null @@ -222,6 +205,19 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> spanIframeId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListPage.kt index 0018bcf6..40522df7 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListPage.kt @@ -2,171 +2,115 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.SpanIframeService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all span_iframes. The span_iframes are sorted by creation date, with the most - * recently-created span_iframes coming first - */ +/** @see [SpanIframeService.list] */ class SpanIframeListPage private constructor( - private val spanIframesService: SpanIframeService, + private val service: SpanIframeService, private val params: SpanIframeListParams, - private val response: Response, + private val response: SpanIframeListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [SpanIframeListPageResponse], but gracefully handles missing data. + * + * @see [SpanIframeListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is SpanIframeListPage && spanIframesService == other.spanIframesService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(spanIframesService, params, response) /* spotless:on */ - - override fun toString() = - "SpanIframeListPage{spanIframesService=$spanIframesService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - SpanIframeListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - SpanIframeListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { spanIframesService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of( - spanIframesService: SpanIframeService, - params: SpanIframeListParams, - response: Response, - ) = SpanIframeListPage(spanIframesService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") - private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): SpanIframeListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): SpanIframeListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [SpanIframeListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [SpanIframeListPage]. */ + class Builder internal constructor() { - companion object { + private var service: SpanIframeService? = null + private var params: SpanIframeListParams? = null + private var response: SpanIframeListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [SpanIframeListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(spanIframeListPage: SpanIframeListPage) = apply { + service = spanIframeListPage.service + params = spanIframeListPage.params + response = spanIframeListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: SpanIframeService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: SpanIframeListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: SpanIframeListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [SpanIframeListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SpanIframeListPage = + SpanIframeListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: SpanIframeListPage) : Iterable { @@ -187,4 +131,17 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is SpanIframeListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "SpanIframeListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListPageAsync.kt index b7d9bd94..7a564ec0 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListPageAsync.kt @@ -2,175 +2,119 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.SpanIframeServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all span_iframes. The span_iframes are sorted by creation date, with the most - * recently-created span_iframes coming first - */ +/** @see [SpanIframeServiceAsync.list] */ class SpanIframeListPageAsync private constructor( - private val spanIframesService: SpanIframeServiceAsync, + private val service: SpanIframeServiceAsync, private val params: SpanIframeListParams, - private val response: Response, + private val response: SpanIframeListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [SpanIframeListPageResponse], but gracefully handles missing data. + * + * @see [SpanIframeListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is SpanIframeListPageAsync && spanIframesService == other.spanIframesService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(spanIframesService, params, response) /* spotless:on */ - - override fun toString() = - "SpanIframeListPageAsync{spanIframesService=$spanIframesService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - SpanIframeListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) - } else { - Optional.of( - SpanIframeListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { spanIframesService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of( - spanIframesService: SpanIframeServiceAsync, - params: SpanIframeListParams, - response: Response, - ) = SpanIframeListPageAsync(spanIframesService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") - private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): SpanIframeListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): SpanIframeListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [SpanIframeListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [SpanIframeListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: SpanIframeServiceAsync? = null + private var params: SpanIframeListParams? = null + private var response: SpanIframeListPageResponse? = null - /** - * Returns a mutable builder for constructing an instance of [SpanIframeListPageAsync]. - */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(spanIframeListPageAsync: SpanIframeListPageAsync) = apply { + service = spanIframeListPageAsync.service + params = spanIframeListPageAsync.params + response = spanIframeListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: SpanIframeServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: SpanIframeListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: SpanIframeListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [SpanIframeListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SpanIframeListPageAsync = + SpanIframeListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: SpanIframeListPageAsync) { @@ -198,4 +142,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is SpanIframeListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "SpanIframeListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListPageResponse.kt new file mode 100644 index 00000000..f6d22bda --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListPageResponse.kt @@ -0,0 +1,194 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class SpanIframeListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") + @ExcludeMissing + objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of span_iframe objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [SpanIframeListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SpanIframeListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(spanIframeListPageResponse: SpanIframeListPageResponse) = apply { + objects = spanIframeListPageResponse.objects.map { it.toMutableList() } + additionalProperties = spanIframeListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of span_iframe objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [SpanIFrame] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: SpanIFrame) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [SpanIframeListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SpanIframeListPageResponse = + SpanIframeListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): SpanIframeListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is SpanIframeListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SpanIframeListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListParams.kt index fdfa8f86..7ad05511 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListParams.kt @@ -2,22 +2,10 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -75,31 +63,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - endingBefore?.let { put("ending_before", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - orgName?.let { put("org_name", it) } - spanIframeName?.let { put("span_iframe_name", it) } - startingAfter?.let { put("starting_after", it) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -111,7 +74,6 @@ private constructor( } /** A builder for [SpanIframeListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var endingBefore: String? = null @@ -317,17 +279,39 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + endingBefore?.let { put("ending_before", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + orgName?.let { put("org_name", it) } + spanIframeName?.let { put("span_iframe_name", it) } + startingAfter?.let { put("starting_after", it) } + putAll(additionalQueryParams) + } + .build() + /** * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -342,15 +326,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -366,7 +347,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -383,51 +363,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeReplaceParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeReplaceParams.kt index 0b05cad8..5b2265b4 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeReplaceParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeReplaceParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -115,33 +113,295 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [SpanIframeReplaceParams]. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SpanIframeReplaceParams]. */ + 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(spanIframeReplaceParams: SpanIframeReplaceParams) = apply { + body = spanIframeReplaceParams.body.toBuilder() + additionalHeaders = spanIframeReplaceParams.additionalHeaders.toBuilder() + additionalQueryParams = spanIframeReplaceParams.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: + * - [name] + * - [projectId] + * - [url] + * - [description] + * - [postMessage] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the span iframe */ + fun name(name: String) = apply { body.name(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 { body.name(name) } + + /** Unique identifier for the project that the span iframe belongs under */ + fun projectId(projectId: String) = apply { body.projectId(projectId) } + + /** + * Sets [Builder.projectId] to an arbitrary JSON value. + * + * You should usually call [Builder.projectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } + + /** URL to embed the project viewer in an iframe */ + fun url(url: String) = apply { body.url(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 { body.url(url) } + + /** Textual description of the span iframe */ + fun description(description: String?) = apply { body.description(description) } + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { body.description(description) } + + /** + * Whether to post messages to the iframe containing the span's data. This is useful when + * you want to render more data than fits in the URL. + */ + fun postMessage(postMessage: Boolean?) = apply { body.postMessage(postMessage) } + + /** + * Alias for [Builder.postMessage]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun postMessage(postMessage: Boolean) = postMessage(postMessage as Boolean?) + + /** Alias for calling [Builder.postMessage] with `postMessage.orElse(null)`. */ + fun postMessage(postMessage: Optional) = postMessage(postMessage.getOrNull()) + + /** + * Sets [Builder.postMessage] to an arbitrary JSON value. + * + * You should usually call [Builder.postMessage] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun postMessage(postMessage: JsonField) = apply { body.postMessage(postMessage) } + + 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 [SpanIframeReplaceParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SpanIframeReplaceParams = + SpanIframeReplaceParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body override fun _headers(): Headers = additionalHeaders override fun _queryParams(): QueryParams = additionalQueryParams - @NoAutoDetect class Body - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("project_id") - @ExcludeMissing - private val projectId: JsonField = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing private val url: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("post_message") - @ExcludeMissing - private val postMessage: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val projectId: JsonField, + private val url: JsonField, + private val description: JsonField, + private val postMessage: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("project_id") + @ExcludeMissing + projectId: JsonField = JsonMissing.of(), + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("post_message") + @ExcludeMissing + postMessage: JsonField = JsonMissing.of(), + ) : this(name, projectId, url, description, postMessage, mutableMapOf()) + /** * Name of the span iframe * @@ -172,8 +432,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + fun description(): Optional = description.getOptional("description") /** * Whether to post messages to the iframe containing the span's data. This is useful when @@ -182,8 +441,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun postMessage(): Optional = - Optional.ofNullable(postMessage.getNullable("post_message")) + fun postMessage(): Optional = postMessage.getOptional("post_message") /** * Returns the raw JSON value of [name]. @@ -224,24 +482,15 @@ private constructor( @ExcludeMissing fun _postMessage(): JsonField = postMessage + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - name() - projectId() - url() - description() - postMessage() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -400,271 +649,63 @@ private constructor( checkRequired("url", url), description, postMessage, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply } - return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && url == other.url && description == other.description && postMessage == other.postMessage && additionalProperties == other.additionalProperties /* spotless:on */ + name() + projectId() + url() + description() + postMessage() + validated = true } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, projectId, url, description, postMessage, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{name=$name, projectId=$projectId, url=$url, description=$description, postMessage=$postMessage, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } /** - * Returns a mutable builder for constructing an instance of [SpanIframeReplaceParams]. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .url() - * ``` + * Used for best match union deserialization. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [SpanIframeReplaceParams]. */ - @NoAutoDetect - 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(spanIframeReplaceParams: SpanIframeReplaceParams) = apply { - body = spanIframeReplaceParams.body.toBuilder() - additionalHeaders = spanIframeReplaceParams.additionalHeaders.toBuilder() - additionalQueryParams = spanIframeReplaceParams.additionalQueryParams.toBuilder() - } - - /** Name of the span iframe */ - fun name(name: String) = apply { body.name(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 { body.name(name) } - - /** Unique identifier for the project that the span iframe belongs under */ - fun projectId(projectId: String) = apply { body.projectId(projectId) } - - /** - * Sets [Builder.projectId] to an arbitrary JSON value. - * - * You should usually call [Builder.projectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun projectId(projectId: JsonField) = apply { body.projectId(projectId) } - - /** URL to embed the project viewer in an iframe */ - fun url(url: String) = apply { body.url(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 { body.url(url) } - - /** Textual description of the span iframe */ - fun description(description: String?) = apply { body.description(description) } - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun description(description: JsonField) = apply { body.description(description) } - - /** - * Whether to post messages to the iframe containing the span's data. This is useful when - * you want to render more data than fits in the URL. - */ - fun postMessage(postMessage: Boolean?) = apply { body.postMessage(postMessage) } - - /** - * Alias for [Builder.postMessage]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun postMessage(postMessage: Boolean) = postMessage(postMessage as Boolean?) - - /** Alias for calling [Builder.postMessage] with `postMessage.orElse(null)`. */ - fun postMessage(postMessage: Optional) = postMessage(postMessage.getOrNull()) - - /** - * Sets [Builder.postMessage] to an arbitrary JSON value. - * - * You should usually call [Builder.postMessage] with a well-typed [Boolean] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun postMessage(postMessage: JsonField) = apply { body.postMessage(postMessage) } - - 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) - } + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (projectId.asKnown().isPresent) 1 else 0) + + (if (url.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (postMessage.asKnown().isPresent) 1 else 0) - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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) + return /* spotless:off */ other is Body && name == other.name && projectId == other.projectId && url == other.url && description == other.description && postMessage == other.postMessage && additionalProperties == other.additionalProperties /* spotless:on */ } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, projectId, url, description, postMessage, additionalProperties) } + /* spotless:on */ - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + override fun hashCode(): Int = hashCode - /** - * Returns an immutable instance of [SpanIframeReplaceParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .projectId() - * .url() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): SpanIframeReplaceParams = - SpanIframeReplaceParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + override fun toString() = + "Body{name=$name, projectId=$projectId, url=$url, description=$description, postMessage=$postMessage, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeRetrieveParams.kt index 003e528f..63c737bb 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> spanIframeId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [SpanIframeRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var spanIframeId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> spanIframeId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeUpdateParams.kt index d5fa952c..7236e5a9 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeUpdateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeUpdateParams.kt @@ -6,18 +6,16 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 @@ -105,268 +103,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> spanIframeId - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("post_message") - @ExcludeMissing - private val postMessage: JsonField = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing private val url: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * Textual description of the span iframe - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - /** - * Name of the span iframe - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** - * Whether to post messages to the iframe containing the span's data. This is useful when - * you want to render more data than fits in the URL. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun postMessage(): Optional = - Optional.ofNullable(postMessage.getNullable("post_message")) - - /** - * URL to embed the project viewer in an iframe - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun url(): Optional = Optional.ofNullable(url.getNullable("url")) - - /** - * Returns the raw JSON value of [description]. - * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description - - /** - * Returns the raw JSON value of [name]. - * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - /** - * Returns the raw JSON value of [postMessage]. - * - * Unlike [postMessage], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("post_message") - @ExcludeMissing - fun _postMessage(): JsonField = postMessage - - /** - * 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 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - description() - name() - postMessage() - url() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Body]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var description: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var postMessage: JsonField = JsonMissing.of() - private var url: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - description = body.description - name = body.name - postMessage = body.postMessage - url = body.url - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** Textual description of the span iframe */ - fun description(description: String?) = description(JsonField.ofNullable(description)) - - /** Alias for calling [Builder.description] with `description.orElse(null)`. */ - fun description(description: Optional) = description(description.getOrNull()) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun description(description: JsonField) = apply { - this.description = description - } - - /** Name of the span iframe */ - 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 } - - /** - * Whether to post messages to the iframe containing the span's data. This is useful - * when you want to render more data than fits in the URL. - */ - fun postMessage(postMessage: Boolean?) = postMessage(JsonField.ofNullable(postMessage)) - - /** - * Alias for [Builder.postMessage]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun postMessage(postMessage: Boolean) = postMessage(postMessage as Boolean?) - - /** Alias for calling [Builder.postMessage] with `postMessage.orElse(null)`. */ - fun postMessage(postMessage: Optional) = postMessage(postMessage.getOrNull()) - - /** - * Sets [Builder.postMessage] to an arbitrary JSON value. - * - * You should usually call [Builder.postMessage] with a well-typed [Boolean] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun postMessage(postMessage: JsonField) = apply { - this.postMessage = postMessage - } - - /** URL to embed the project viewer in an iframe */ - fun url(url: String?) = url(JsonField.ofNullable(url)) - - /** Alias for calling [Builder.url] with `url.orElse(null)`. */ - fun url(url: Optional) = url(url.getOrNull()) - - /** - * Sets [Builder.url] to an arbitrary JSON value. - * - * You should usually call [Builder.url] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun url(url: JsonField) = apply { this.url = url } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Body = - Body(description, name, postMessage, url, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && description == other.description && name == other.name && postMessage == other.postMessage && url == other.url && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(description, name, postMessage, url, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{description=$description, name=$name, postMessage=$postMessage, url=$url, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -383,7 +119,6 @@ private constructor( } /** A builder for [SpanIframeUpdateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var spanIframeId: String? = null @@ -402,6 +137,18 @@ private constructor( /** SpanIframe id */ fun spanIframeId(spanIframeId: String) = apply { this.spanIframeId = spanIframeId } + /** + * 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: + * - [description] + * - [name] + * - [postMessage] + * - [url] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** Textual description of the span iframe */ fun description(description: String?) = apply { body.description(description) } @@ -608,6 +355,295 @@ private constructor( ) } + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> spanIframeId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val description: JsonField, + private val name: JsonField, + private val postMessage: JsonField, + private val url: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("post_message") + @ExcludeMissing + postMessage: JsonField = JsonMissing.of(), + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + ) : this(description, name, postMessage, url, mutableMapOf()) + + /** + * Textual description of the span iframe + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * Name of the span iframe + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Whether to post messages to the iframe containing the span's data. This is useful when + * you want to render more data than fits in the URL. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun postMessage(): Optional = postMessage.getOptional("post_message") + + /** + * URL to embed the project viewer in an iframe + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun url(): Optional = url.getOptional("url") + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [postMessage]. + * + * Unlike [postMessage], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("post_message") + @ExcludeMissing + fun _postMessage(): JsonField = postMessage + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var description: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var postMessage: JsonField = JsonMissing.of() + private var url: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + description = body.description + name = body.name + postMessage = body.postMessage + url = body.url + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Textual description of the span iframe */ + fun description(description: String?) = description(JsonField.ofNullable(description)) + + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + + /** Name of the span iframe */ + 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 } + + /** + * Whether to post messages to the iframe containing the span's data. This is useful + * when you want to render more data than fits in the URL. + */ + fun postMessage(postMessage: Boolean?) = postMessage(JsonField.ofNullable(postMessage)) + + /** + * Alias for [Builder.postMessage]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun postMessage(postMessage: Boolean) = postMessage(postMessage as Boolean?) + + /** Alias for calling [Builder.postMessage] with `postMessage.orElse(null)`. */ + fun postMessage(postMessage: Optional) = postMessage(postMessage.getOrNull()) + + /** + * Sets [Builder.postMessage] to an arbitrary JSON value. + * + * You should usually call [Builder.postMessage] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun postMessage(postMessage: JsonField) = apply { + this.postMessage = postMessage + } + + /** URL to embed the project viewer in an iframe */ + fun url(url: String?) = url(JsonField.ofNullable(url)) + + /** Alias for calling [Builder.url] with `url.orElse(null)`. */ + fun url(url: Optional) = url(url.getOrNull()) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun url(url: JsonField) = apply { this.url = url } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body(description, name, postMessage, url, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + description() + name() + postMessage() + url() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (description.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (postMessage.asKnown().isPresent) 1 else 0) + + (if (url.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && description == other.description && name == other.name && postMessage == other.postMessage && url == other.url && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(description, name, postMessage, url, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{description=$description, name=$name, postMessage=$postMessage, url=$url, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanType.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanType.kt index 2c558123..33527e47 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanType.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanType.kt @@ -116,6 +116,32 @@ class SpanType @JsonCreator private constructor(private val value: JsonField = JsonMissing.of(), - @JsonProperty("dataset_url") - @ExcludeMissing - private val datasetUrl: JsonField = JsonMissing.of(), - @JsonProperty("project_name") - @ExcludeMissing - private val projectName: JsonField = JsonMissing.of(), - @JsonProperty("project_url") - @ExcludeMissing - private val projectUrl: JsonField = JsonMissing.of(), - @JsonProperty("data_summary") - @ExcludeMissing - private val dataSummary: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val datasetName: JsonField, + private val datasetUrl: JsonField, + private val projectName: JsonField, + private val projectUrl: JsonField, + private val dataSummary: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("dataset_name") + @ExcludeMissing + datasetName: JsonField = JsonMissing.of(), + @JsonProperty("dataset_url") + @ExcludeMissing + datasetUrl: JsonField = JsonMissing.of(), + @JsonProperty("project_name") + @ExcludeMissing + projectName: JsonField = JsonMissing.of(), + @JsonProperty("project_url") + @ExcludeMissing + projectUrl: JsonField = JsonMissing.of(), + @JsonProperty("data_summary") + @ExcludeMissing + dataSummary: JsonField = JsonMissing.of(), + ) : this(datasetName, datasetUrl, projectName, projectUrl, dataSummary, mutableMapOf()) + /** * Name of the dataset * @@ -80,8 +85,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun dataSummary(): Optional = - Optional.ofNullable(dataSummary.getNullable("data_summary")) + fun dataSummary(): Optional = dataSummary.getOptional("data_summary") /** * Returns the raw JSON value of [datasetName]. @@ -124,24 +128,15 @@ private constructor( @ExcludeMissing fun _dataSummary(): JsonField = dataSummary + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SummarizeDatasetResponse = apply { - if (validated) { - return@apply - } - - datasetName() - datasetUrl() - projectName() - projectUrl() - dataSummary().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -287,10 +282,46 @@ private constructor( checkRequired("projectName", projectName), checkRequired("projectUrl", projectUrl), dataSummary, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): SummarizeDatasetResponse = apply { + if (validated) { + return@apply + } + + datasetName() + datasetUrl() + projectName() + projectUrl() + dataSummary().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (datasetName.asKnown().isPresent) 1 else 0) + + (if (datasetUrl.asKnown().isPresent) 1 else 0) + + (if (projectName.asKnown().isPresent) 1 else 0) + + (if (projectUrl.asKnown().isPresent) 1 else 0) + + (dataSummary.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SummarizeExperimentResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SummarizeExperimentResponse.kt index 1c8a412a..05066a50 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SummarizeExperimentResponse.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SummarizeExperimentResponse.kt @@ -6,48 +6,61 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 /** Summary of an experiment */ -@NoAutoDetect class SummarizeExperimentResponse -@JsonCreator private constructor( - @JsonProperty("experiment_name") - @ExcludeMissing - private val experimentName: JsonField = JsonMissing.of(), - @JsonProperty("experiment_url") - @ExcludeMissing - private val experimentUrl: JsonField = JsonMissing.of(), - @JsonProperty("project_name") - @ExcludeMissing - private val projectName: JsonField = JsonMissing.of(), - @JsonProperty("project_url") - @ExcludeMissing - private val projectUrl: JsonField = JsonMissing.of(), - @JsonProperty("comparison_experiment_name") - @ExcludeMissing - private val comparisonExperimentName: JsonField = JsonMissing.of(), - @JsonProperty("metrics") - @ExcludeMissing - private val metrics: JsonField = JsonMissing.of(), - @JsonProperty("scores") - @ExcludeMissing - private val scores: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val experimentName: JsonField, + private val experimentUrl: JsonField, + private val projectName: JsonField, + private val projectUrl: JsonField, + private val comparisonExperimentName: JsonField, + private val metrics: JsonField, + private val scores: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("experiment_name") + @ExcludeMissing + experimentName: JsonField = JsonMissing.of(), + @JsonProperty("experiment_url") + @ExcludeMissing + experimentUrl: JsonField = JsonMissing.of(), + @JsonProperty("project_name") + @ExcludeMissing + projectName: JsonField = JsonMissing.of(), + @JsonProperty("project_url") + @ExcludeMissing + projectUrl: JsonField = JsonMissing.of(), + @JsonProperty("comparison_experiment_name") + @ExcludeMissing + comparisonExperimentName: JsonField = JsonMissing.of(), + @JsonProperty("metrics") @ExcludeMissing metrics: JsonField = JsonMissing.of(), + @JsonProperty("scores") @ExcludeMissing scores: JsonField = JsonMissing.of(), + ) : this( + experimentName, + experimentUrl, + projectName, + projectUrl, + comparisonExperimentName, + metrics, + scores, + mutableMapOf(), + ) + /** * Name of the experiment * @@ -87,7 +100,7 @@ private constructor( * server responded with an unexpected value). */ fun comparisonExperimentName(): Optional = - Optional.ofNullable(comparisonExperimentName.getNullable("comparison_experiment_name")) + comparisonExperimentName.getOptional("comparison_experiment_name") /** * Summary of the experiment's metrics @@ -95,7 +108,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun metrics(): Optional = Optional.ofNullable(metrics.getNullable("metrics")) + fun metrics(): Optional = metrics.getOptional("metrics") /** * Summary of the experiment's scores @@ -103,7 +116,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun scores(): Optional = Optional.ofNullable(scores.getNullable("scores")) + fun scores(): Optional = scores.getOptional("scores") /** * Returns the raw JSON value of [experimentName]. @@ -163,26 +176,15 @@ private constructor( */ @JsonProperty("scores") @ExcludeMissing fun _scores(): JsonField = scores + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SummarizeExperimentResponse = apply { - if (validated) { - return@apply - } - - experimentName() - experimentUrl() - projectName() - projectUrl() - comparisonExperimentName() - metrics().ifPresent { it.validate() } - scores().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -371,33 +373,62 @@ private constructor( comparisonExperimentName, metrics, scores, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): SummarizeExperimentResponse = apply { + if (validated) { + return@apply + } + + experimentName() + experimentUrl() + projectName() + projectUrl() + comparisonExperimentName() + metrics().ifPresent { it.validate() } + scores().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (experimentName.asKnown().isPresent) 1 else 0) + + (if (experimentUrl.asKnown().isPresent) 1 else 0) + + (if (projectName.asKnown().isPresent) 1 else 0) + + (if (projectUrl.asKnown().isPresent) 1 else 0) + + (if (comparisonExperimentName.asKnown().isPresent) 1 else 0) + + (metrics.asKnown().getOrNull()?.validity() ?: 0) + + (scores.asKnown().getOrNull()?.validity() ?: 0) + /** Summary of the experiment's metrics */ - @NoAutoDetect class Metrics @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Metrics = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -443,6 +474,34 @@ private constructor( fun build(): Metrics = Metrics(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Metrics = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -461,28 +520,17 @@ private constructor( } /** Summary of the experiment's scores */ - @NoAutoDetect class Scores @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Scores = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -528,6 +576,34 @@ private constructor( fun build(): Scores = Scores(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Scores = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/TopLevelHelloWorldParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/TopLevelHelloWorldParams.kt index e6ef1cd1..07da14b6 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/TopLevelHelloWorldParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/TopLevelHelloWorldParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams @@ -19,10 +18,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { @@ -34,7 +29,6 @@ private constructor( } /** A builder for [TopLevelHelloWorldParams]. */ - @NoAutoDetect class Builder internal constructor() { private var additionalHeaders: Headers.Builder = Headers.builder() @@ -153,6 +147,10 @@ private constructor( TopLevelHelloWorldParams(additionalHeaders.build(), additionalQueryParams.build()) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/User.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/User.kt index ac80f854..d2a2db23 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/User.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/User.kt @@ -6,41 +6,43 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class User -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("avatar_url") - @ExcludeMissing - private val avatarUrl: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("email") @ExcludeMissing private val email: JsonField = JsonMissing.of(), - @JsonProperty("family_name") - @ExcludeMissing - private val familyName: JsonField = JsonMissing.of(), - @JsonProperty("given_name") - @ExcludeMissing - private val givenName: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val avatarUrl: JsonField, + private val created: JsonField, + private val email: JsonField, + private val familyName: JsonField, + private val givenName: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("avatar_url") @ExcludeMissing avatarUrl: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("email") @ExcludeMissing email: JsonField = JsonMissing.of(), + @JsonProperty("family_name") + @ExcludeMissing + familyName: JsonField = JsonMissing.of(), + @JsonProperty("given_name") @ExcludeMissing givenName: JsonField = JsonMissing.of(), + ) : this(id, avatarUrl, created, email, familyName, givenName, mutableMapOf()) + /** * Unique identifier for the user * @@ -55,7 +57,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun avatarUrl(): Optional = Optional.ofNullable(avatarUrl.getNullable("avatar_url")) + fun avatarUrl(): Optional = avatarUrl.getOptional("avatar_url") /** * Date of user creation @@ -63,7 +65,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * The user's email @@ -71,7 +73,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun email(): Optional = Optional.ofNullable(email.getNullable("email")) + fun email(): Optional = email.getOptional("email") /** * Family name of the user @@ -79,7 +81,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun familyName(): Optional = Optional.ofNullable(familyName.getNullable("family_name")) + fun familyName(): Optional = familyName.getOptional("family_name") /** * Given name of the user @@ -87,7 +89,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun givenName(): Optional = Optional.ofNullable(givenName.getNullable("given_name")) + fun givenName(): Optional = givenName.getOptional("given_name") /** * Returns the raw JSON value of [id]. @@ -131,25 +133,15 @@ private constructor( */ @JsonProperty("given_name") @ExcludeMissing fun _givenName(): JsonField = givenName + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): User = apply { - if (validated) { - return@apply - } - - id() - avatarUrl() - created() - email() - familyName() - givenName() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -312,10 +304,48 @@ private constructor( email, familyName, givenName, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): User = apply { + if (validated) { + return@apply + } + + id() + avatarUrl() + created() + email() + familyName() + givenName() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (avatarUrl.asKnown().isPresent) 1 else 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (email.asKnown().isPresent) 1 else 0) + + (if (familyName.asKnown().isPresent) 1 else 0) + + (if (givenName.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListPage.kt index c1feb5eb..25aaa0e1 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListPage.kt @@ -2,161 +2,115 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.UserService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all users. The users are sorted by creation date, with the most recently-created users - * coming first - */ +/** @see [UserService.list] */ class UserListPage private constructor( - private val usersService: UserService, + private val service: UserService, private val params: UserListParams, - private val response: Response, + private val response: UserListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [UserListPageResponse], but gracefully handles missing data. + * + * @see [UserListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is UserListPage && usersService == other.usersService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(usersService, params, response) /* spotless:on */ - - override fun toString() = - "UserListPage{usersService=$usersService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - UserListParams.builder().from(params).endingBefore(objects().first().id()).build() - ) - } else { - Optional.of( - UserListParams.builder().from(params).startingAfter(objects().last().id()).build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { usersService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(usersService: UserService, params: UserListParams, response: Response) = - UserListPage(usersService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): UserListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): UserListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [UserListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [UserListPage]. */ + class Builder internal constructor() { - companion object { + private var service: UserService? = null + private var params: UserListParams? = null + private var response: UserListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [UserListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(userListPage: UserListPage) = apply { + service = userListPage.service + params = userListPage.params + response = userListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: UserService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: UserListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: UserListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [UserListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UserListPage = + UserListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: UserListPage) : Iterable { @@ -177,4 +131,16 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is UserListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = "UserListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListPageAsync.kt index 23c28a26..412a21a0 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListPageAsync.kt @@ -2,163 +2,119 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.UserServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all users. The users are sorted by creation date, with the most recently-created users - * coming first - */ +/** @see [UserServiceAsync.list] */ class UserListPageAsync private constructor( - private val usersService: UserServiceAsync, + private val service: UserServiceAsync, private val params: UserListParams, - private val response: Response, + private val response: UserListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [UserListPageResponse], but gracefully handles missing data. + * + * @see [UserListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is UserListPageAsync && usersService == other.usersService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(usersService, params, response) /* spotless:on */ - - override fun toString() = - "UserListPageAsync{usersService=$usersService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - UserListParams.builder().from(params).endingBefore(objects().first().id()).build() - ) - } else { - Optional.of( - UserListParams.builder().from(params).startingAfter(objects().last().id()).build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { usersService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(usersService: UserServiceAsync, params: UserListParams, response: Response) = - UserListPageAsync(usersService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): UserListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): UserListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [UserListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [UserListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: UserServiceAsync? = null + private var params: UserListParams? = null + private var response: UserListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [UserListPageAsync]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(userListPageAsync: UserListPageAsync) = apply { + service = userListPageAsync.service + params = userListPageAsync.params + response = userListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: UserServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: UserListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: UserListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [UserListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UserListPageAsync = + UserListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: UserListPageAsync) { @@ -186,4 +142,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is UserListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "UserListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListPageResponse.kt new file mode 100644 index 00000000..b38d950e --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListPageResponse.kt @@ -0,0 +1,192 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class UserListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") @ExcludeMissing objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of user objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [UserListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UserListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(userListPageResponse: UserListPageResponse) = apply { + objects = userListPageResponse.objects.map { it.toMutableList() } + additionalProperties = userListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of user objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [User] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: User) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UserListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UserListPageResponse = + UserListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): UserListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is UserListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UserListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListParams.kt index 55618ca7..70081294 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListParams.kt @@ -2,22 +2,10 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -92,63 +80,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - email?.accept( - object : Email.Visitor { - override fun visitString(string: String) { - put("email", string) - } - - override fun visitStrings(strings: List) { - put("email", strings.joinToString(",")) - } - } - ) - endingBefore?.let { put("ending_before", it) } - familyName?.accept( - object : FamilyName.Visitor { - override fun visitString(string: String) { - put("family_name", string) - } - - override fun visitStrings(strings: List) { - put("family_name", strings.joinToString(",")) - } - } - ) - givenName?.accept( - object : GivenName.Visitor { - override fun visitString(string: String) { - put("given_name", string) - } - - override fun visitStrings(strings: List) { - put("given_name", strings.joinToString(",")) - } - } - ) - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - orgName?.let { put("org_name", it) } - startingAfter?.let { put("starting_after", it) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -160,7 +91,6 @@ private constructor( } /** A builder for [UserListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var email: Email? = null @@ -410,17 +340,71 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + email?.accept( + object : Email.Visitor { + override fun visitString(string: String) { + put("email", string) + } + + override fun visitStrings(strings: List) { + put("email", strings.joinToString(",")) + } + } + ) + endingBefore?.let { put("ending_before", it) } + familyName?.accept( + object : FamilyName.Visitor { + override fun visitString(string: String) { + put("family_name", string) + } + + override fun visitStrings(strings: List) { + put("family_name", strings.joinToString(",")) + } + } + ) + givenName?.accept( + object : GivenName.Visitor { + override fun visitString(string: String) { + put("given_name", string) + } + + override fun visitStrings(strings: List) { + put("given_name", strings.joinToString(",")) + } + } + ) + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + orgName?.let { put("org_name", it) } + startingAfter?.let { put("starting_after", it) } + putAll(additionalQueryParams) + } + .build() + /** * Email of the user to search for. You may pass the param multiple times to filter for more * than one email */ - @JsonDeserialize(using = Email.Deserializer::class) - @JsonSerialize(using = Email.Serializer::class) class Email private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -435,15 +419,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Email") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -459,7 +440,6 @@ private constructor( when { string != null -> "Email{string=$string}" strings != null -> "Email{strings=$strings}" - _json != null -> "Email{_unknown=$_json}" else -> throw IllegalStateException("Invalid Email") } @@ -476,52 +456,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Email] to a value of type [T]. - * - * An instance of [Email] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Email: $json") - } - } - - internal class Deserializer : BaseDeserializer(Email::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Email { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Email(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Email(strings = it, _json = json) - } - - return Email(_json = json) - } - } - - internal class Serializer : BaseSerializer(Email::class) { - - override fun serialize( - value: Email, - 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 Email") - } - } } } @@ -529,13 +463,10 @@ private constructor( * Family name of the user to search for. You may pass the param multiple times to filter for * more than one family name */ - @JsonDeserialize(using = FamilyName.Deserializer::class) - @JsonSerialize(using = FamilyName.Serializer::class) class FamilyName private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -550,15 +481,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid FamilyName") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -574,7 +502,6 @@ private constructor( when { string != null -> "FamilyName{string=$string}" strings != null -> "FamilyName{strings=$strings}" - _json != null -> "FamilyName{_unknown=$_json}" else -> throw IllegalStateException("Invalid FamilyName") } @@ -593,52 +520,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [FamilyName] to a value of type [T]. - * - * An instance of [FamilyName] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown FamilyName: $json") - } - } - - internal class Deserializer : BaseDeserializer(FamilyName::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): FamilyName { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return FamilyName(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return FamilyName(strings = it, _json = json) - } - - return FamilyName(_json = json) - } - } - - internal class Serializer : BaseSerializer(FamilyName::class) { - - override fun serialize( - value: FamilyName, - 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 FamilyName") - } - } } } @@ -646,13 +527,10 @@ private constructor( * Given name of the user to search for. You may pass the param multiple times to filter for * more than one given name */ - @JsonDeserialize(using = GivenName.Deserializer::class) - @JsonSerialize(using = GivenName.Serializer::class) class GivenName private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -667,15 +545,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid GivenName") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -691,7 +566,6 @@ private constructor( when { string != null -> "GivenName{string=$string}" strings != null -> "GivenName{strings=$strings}" - _json != null -> "GivenName{_unknown=$_json}" else -> throw IllegalStateException("Invalid GivenName") } @@ -710,52 +584,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [GivenName] to a value of type [T]. - * - * An instance of [GivenName] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown GivenName: $json") - } - } - - internal class Deserializer : BaseDeserializer(GivenName::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): GivenName { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return GivenName(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return GivenName(strings = it, _json = json) - } - - return GivenName(_json = json) - } - } - - internal class Serializer : BaseSerializer(GivenName::class) { - - override fun serialize( - value: GivenName, - 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 GivenName") - } - } } } @@ -763,13 +591,10 @@ private constructor( * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -784,15 +609,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -808,7 +630,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -825,51 +646,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserRetrieveParams.kt index 4d668314..3a97c821 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -24,17 +23,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> userId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -51,7 +39,6 @@ private constructor( } /** A builder for [UserRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var userId: String? = null @@ -186,6 +173,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> userId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/View.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/View.kt index f7439666..5ca9dc21 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/View.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/View.kt @@ -7,53 +7,65 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkRequired -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class View -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("view_type") - @ExcludeMissing - private val viewType: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("deleted_at") - @ExcludeMissing - private val deletedAt: JsonField = JsonMissing.of(), - @JsonProperty("options") - @ExcludeMissing - private val options: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonProperty("view_data") - @ExcludeMissing - private val viewData: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val name: JsonField, + private val objectId: JsonField, + private val objectType: JsonField, + private val viewType: JsonField, + private val created: JsonField, + private val deletedAt: JsonField, + private val options: JsonField, + private val userId: JsonField, + private val viewData: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("object_id") @ExcludeMissing objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("view_type") @ExcludeMissing viewType: JsonField = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("deleted_at") + @ExcludeMissing + deletedAt: JsonField = JsonMissing.of(), + @JsonProperty("options") @ExcludeMissing options: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + @JsonProperty("view_data") @ExcludeMissing viewData: JsonField = JsonMissing.of(), + ) : this( + id, + name, + objectId, + objectType, + viewType, + created, + deletedAt, + options, + userId, + viewData, + mutableMapOf(), + ) + /** * Unique identifier for the view * @@ -92,7 +104,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun viewType(): Optional = Optional.ofNullable(viewType.getNullable("view_type")) + fun viewType(): Optional = viewType.getOptional("view_type") /** * Date of view creation @@ -100,7 +112,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + fun created(): Optional = created.getOptional("created") /** * Date of role deletion, or null if the role is still active @@ -108,8 +120,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun deletedAt(): Optional = - Optional.ofNullable(deletedAt.getNullable("deleted_at")) + fun deletedAt(): Optional = deletedAt.getOptional("deleted_at") /** * Options for the view in the app @@ -117,7 +128,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun options(): Optional = Optional.ofNullable(options.getNullable("options")) + fun options(): Optional = options.getOptional("options") /** * Identifies the user who created the view @@ -125,7 +136,7 @@ private constructor( * @throws BraintrustInvalidDataException 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") /** * The view definition @@ -133,7 +144,7 @@ private constructor( * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun viewData(): Optional = Optional.ofNullable(viewData.getNullable("view_data")) + fun viewData(): Optional = viewData.getOptional("view_data") /** * Returns the raw JSON value of [id]. @@ -209,29 +220,15 @@ private constructor( */ @JsonProperty("view_data") @ExcludeMissing fun _viewData(): JsonField = viewData + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): View = apply { - if (validated) { - return@apply - } - - id() - name() - objectId() - objectType() - viewType() - created() - deletedAt() - options().ifPresent { it.validate() } - userId() - viewData().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -465,10 +462,56 @@ private constructor( options, userId, viewData, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): View = apply { + if (validated) { + return@apply + } + + id() + name() + objectId() + objectType().validate() + viewType().ifPresent { it.validate() } + created() + deletedAt() + options().ifPresent { it.validate() } + userId() + viewData().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (viewType.asKnown().getOrNull()?.validity() ?: 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (deletedAt.asKnown().isPresent) 1 else 0) + + (options.asKnown().getOrNull()?.validity() ?: 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + (viewData.asKnown().getOrNull()?.validity() ?: 0) + /** Type of table that the view corresponds to. */ class ViewType @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -611,6 +654,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ViewType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewCreateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewCreateParams.kt index da386fa5..608ecf69 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewCreateParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewCreateParams.kt @@ -7,19 +7,17 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -161,422 +159,281 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun toBuilder() = Builder().from(this) - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("view_type") - @ExcludeMissing - private val viewType: JsonField = JsonMissing.of(), - @JsonProperty("deleted_at") - @ExcludeMissing - private val deletedAt: JsonField = JsonMissing.of(), - @JsonProperty("options") - @ExcludeMissing - private val options: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonProperty("view_data") - @ExcludeMissing - private val viewData: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + companion object { /** - * Name of the view + * Returns a mutable builder for constructing an instance of [ViewCreateParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .name() + * .objectId() + * .objectType() + * .viewType() + * ``` */ - fun name(): String = name.getRequired("name") + @JvmStatic fun builder() = Builder() + } - /** - * The id of the object the view applies to - * - * @throws BraintrustInvalidDataException 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 objectId(): String = objectId.getRequired("object_id") + /** A builder for [ViewCreateParams]. */ + class Builder internal constructor() { - /** - * The object type that the ACL applies to - * - * @throws BraintrustInvalidDataException 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 objectType(): AclObjectType = objectType.getRequired("object_type") + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - /** - * Type of table that the view corresponds to. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun viewType(): Optional = Optional.ofNullable(viewType.getNullable("view_type")) + @JvmSynthetic + internal fun from(viewCreateParams: ViewCreateParams) = apply { + body = viewCreateParams.body.toBuilder() + additionalHeaders = viewCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = viewCreateParams.additionalQueryParams.toBuilder() + } /** - * Date of role deletion, or null if the role is still active + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [name] + * - [objectId] + * - [objectType] + * - [viewType] + * - [deletedAt] + * - etc. */ - fun deletedAt(): Optional = - Optional.ofNullable(deletedAt.getNullable("deleted_at")) + fun body(body: Body) = apply { this.body = body.toBuilder() } - /** - * Options for the view in the app - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun options(): Optional = Optional.ofNullable(options.getNullable("options")) + /** Name of the view */ + fun name(name: String) = apply { body.name(name) } /** - * Identifies the user who created the view + * Sets [Builder.name] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected 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 userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) + fun name(name: JsonField) = apply { body.name(name) } - /** - * The view definition - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun viewData(): Optional = Optional.ofNullable(viewData.getNullable("view_data")) + /** The id of the object the view applies to */ + fun objectId(objectId: String) = apply { body.objectId(objectId) } /** - * Returns the raw JSON value of [name]. + * Sets [Builder.objectId] to an arbitrary JSON value. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.objectId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun objectId(objectId: JsonField) = apply { body.objectId(objectId) } - /** - * Returns the raw JSON value of [objectId]. - * - * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("object_id") @ExcludeMissing fun _objectId(): JsonField = objectId + /** The object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = apply { body.objectType(objectType) } /** - * Returns the raw JSON value of [objectType]. + * Sets [Builder.objectType] to an arbitrary JSON value. * - * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("object_type") - @ExcludeMissing - fun _objectType(): JsonField = objectType + fun objectType(objectType: JsonField) = apply { body.objectType(objectType) } - /** - * Returns the raw JSON value of [viewType]. - * - * Unlike [viewType], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("view_type") @ExcludeMissing fun _viewType(): JsonField = viewType + /** Type of table that the view corresponds to. */ + fun viewType(viewType: ViewType?) = apply { body.viewType(viewType) } + + /** Alias for calling [Builder.viewType] with `viewType.orElse(null)`. */ + fun viewType(viewType: Optional) = viewType(viewType.getOrNull()) /** - * Returns the raw JSON value of [deletedAt]. + * Sets [Builder.viewType] to an arbitrary JSON value. * - * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.viewType] with a well-typed [ViewType] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("deleted_at") - @ExcludeMissing - fun _deletedAt(): JsonField = deletedAt + fun viewType(viewType: JsonField) = apply { body.viewType(viewType) } + + /** Date of role deletion, or null if the role is still active */ + fun deletedAt(deletedAt: OffsetDateTime?) = apply { body.deletedAt(deletedAt) } + + /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ + fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) /** - * Returns the raw JSON value of [options]. + * Sets [Builder.deletedAt] to an arbitrary JSON value. * - * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = options + fun deletedAt(deletedAt: JsonField) = apply { body.deletedAt(deletedAt) } + + /** Options for the view in the app */ + fun options(options: ViewOptions?) = apply { body.options(options) } + + /** Alias for calling [Builder.options] with `options.orElse(null)`. */ + fun options(options: Optional) = options(options.getOrNull()) /** - * Returns the raw JSON value of [userId]. + * Sets [Builder.options] to an arbitrary JSON value. * - * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.options] with a well-typed [ViewOptions] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + fun options(options: JsonField) = apply { body.options(options) } + + /** Identifies the user who created the view */ + fun userId(userId: String?) = apply { body.userId(userId) } + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) /** - * Returns the raw JSON value of [viewData]. + * Sets [Builder.userId] to an arbitrary JSON value. * - * Unlike [viewData], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("view_data") @ExcludeMissing fun _viewData(): JsonField = viewData + fun userId(userId: JsonField) = apply { body.userId(userId) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** The view definition */ + fun viewData(viewData: ViewData?) = apply { body.viewData(viewData) } - private var validated: Boolean = false + /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ + fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) - fun validate(): Body = apply { - if (validated) { - return@apply - } + /** + * Sets [Builder.viewData] to an arbitrary JSON value. + * + * You should usually call [Builder.viewData] with a well-typed [ViewData] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun viewData(viewData: JsonField) = apply { body.viewData(viewData) } - name() - objectId() - objectType() - viewType() - deletedAt() - options().ifPresent { it.validate() } - userId() - viewData().ifPresent { it.validate() } - validated = true + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) } - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * .objectId() - * .objectType() - * .viewType() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) } - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var name: JsonField? = null - private var objectId: JsonField? = null - private var objectType: JsonField? = null - private var viewType: JsonField? = null - private var deletedAt: JsonField = JsonMissing.of() - private var options: JsonField = JsonMissing.of() - private var userId: JsonField = JsonMissing.of() - private var viewData: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - objectId = body.objectId - objectType = body.objectType - viewType = body.viewType - deletedAt = body.deletedAt - options = body.options - userId = body.userId - viewData = body.viewData - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** Name of the view */ - fun name(name: String) = name(JsonField.of(name)) - - /** - * Sets [Builder.name] to an arbitrary JSON value. - * - * You should usually call [Builder.name] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun name(name: JsonField) = apply { this.name = name } - - /** The id of the object the view applies to */ - fun objectId(objectId: String) = objectId(JsonField.of(objectId)) - - /** - * Sets [Builder.objectId] to an arbitrary JSON value. - * - * You should usually call [Builder.objectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun objectId(objectId: JsonField) = apply { this.objectId = objectId } - - /** The object type that the ACL applies to */ - fun objectType(objectType: AclObjectType) = objectType(JsonField.of(objectType)) - - /** - * Sets [Builder.objectType] to an arbitrary JSON value. - * - * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun objectType(objectType: JsonField) = apply { - this.objectType = objectType + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - /** Type of table that the view corresponds to. */ - fun viewType(viewType: ViewType?) = viewType(JsonField.ofNullable(viewType)) - - /** Alias for calling [Builder.viewType] with `viewType.orElse(null)`. */ - fun viewType(viewType: Optional) = viewType(viewType.getOrNull()) - - /** - * Sets [Builder.viewType] to an arbitrary JSON value. - * - * You should usually call [Builder.viewType] with a well-typed [ViewType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun viewType(viewType: JsonField) = apply { this.viewType = viewType } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - /** Date of role deletion, or null if the role is still active */ - fun deletedAt(deletedAt: OffsetDateTime?) = deletedAt(JsonField.ofNullable(deletedAt)) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ - fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * 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 additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Options for the view in the app */ - fun options(options: ViewOptions?) = options(JsonField.ofNullable(options)) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** Alias for calling [Builder.options] with `options.orElse(null)`. */ - fun options(options: Optional) = options(options.getOrNull()) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** - * Sets [Builder.options] to an arbitrary JSON value. - * - * You should usually call [Builder.options] with a well-typed [ViewOptions] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun options(options: JsonField) = apply { this.options = options } + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Identifies the user who created the view */ - fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ - fun userId(userId: Optional) = userId(userId.getOrNull()) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * 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 replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** The view definition */ - fun viewData(viewData: ViewData?) = viewData(JsonField.ofNullable(viewData)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ - fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.viewData] to an arbitrary JSON value. - * - * You should usually call [Builder.viewData] with a well-typed [ViewData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun viewData(viewData: JsonField) = apply { this.viewData = viewData } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .objectId() - * .objectType() - * .viewType() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("name", name), - checkRequired("objectId", objectId), - checkRequired("objectType", objectType), - checkRequired("viewType", viewType), - deletedAt, - options, - userId, - viewData, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && name == other.name && objectId == other.objectId && objectType == other.objectType && viewType == other.viewType && deletedAt == other.deletedAt && options == other.options && userId == other.userId && viewData == other.viewData && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, objectId, objectType, viewType, deletedAt, options, userId, viewData, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun toString() = - "Body{name=$name, objectId=$objectId, objectType=$objectType, viewType=$viewType, deletedAt=$deletedAt, options=$options, userId=$userId, viewData=$viewData, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - companion object { + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [ViewCreateParams]. + * Returns an immutable instance of [ViewCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java @@ -585,267 +442,466 @@ private constructor( * .objectType() * .viewType() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): ViewCreateParams = + ViewCreateParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) } - /** A builder for [ViewCreateParams]. */ - @NoAutoDetect - class Builder internal constructor() { + fun _body(): Body = body - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + override fun _headers(): Headers = additionalHeaders - @JvmSynthetic - internal fun from(viewCreateParams: ViewCreateParams) = apply { - body = viewCreateParams.body.toBuilder() - additionalHeaders = viewCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = viewCreateParams.additionalQueryParams.toBuilder() - } + override fun _queryParams(): QueryParams = additionalQueryParams - /** Name of the view */ - fun name(name: String) = apply { body.name(name) } + class Body + private constructor( + private val name: JsonField, + private val objectId: JsonField, + private val objectType: JsonField, + private val viewType: JsonField, + private val deletedAt: JsonField, + private val options: JsonField, + private val userId: JsonField, + private val viewData: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("object_id") + @ExcludeMissing + objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("view_type") + @ExcludeMissing + viewType: JsonField = JsonMissing.of(), + @JsonProperty("deleted_at") + @ExcludeMissing + deletedAt: JsonField = JsonMissing.of(), + @JsonProperty("options") + @ExcludeMissing + options: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + @JsonProperty("view_data") + @ExcludeMissing + viewData: JsonField = JsonMissing.of(), + ) : this( + name, + objectId, + objectType, + viewType, + deletedAt, + options, + userId, + viewData, + mutableMapOf(), + ) /** - * Sets [Builder.name] to an arbitrary JSON value. + * Name of the view * - * 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. + * @throws BraintrustInvalidDataException 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(name: JsonField) = apply { body.name(name) } - - /** The id of the object the view applies to */ - fun objectId(objectId: String) = apply { body.objectId(objectId) } + fun name(): String = name.getRequired("name") /** - * Sets [Builder.objectId] to an arbitrary JSON value. + * The id of the object the view applies to * - * You should usually call [Builder.objectId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException 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 objectId(objectId: JsonField) = apply { body.objectId(objectId) } - - /** The object type that the ACL applies to */ - fun objectType(objectType: AclObjectType) = apply { body.objectType(objectType) } + fun objectId(): String = objectId.getRequired("object_id") /** - * Sets [Builder.objectType] to an arbitrary JSON value. + * The object type that the ACL applies to * - * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException 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 objectType(objectType: JsonField) = apply { body.objectType(objectType) } - - /** Type of table that the view corresponds to. */ - fun viewType(viewType: ViewType?) = apply { body.viewType(viewType) } - - /** Alias for calling [Builder.viewType] with `viewType.orElse(null)`. */ - fun viewType(viewType: Optional) = viewType(viewType.getOrNull()) + fun objectType(): AclObjectType = objectType.getRequired("object_type") /** - * Sets [Builder.viewType] to an arbitrary JSON value. + * Type of table that the view corresponds to. * - * You should usually call [Builder.viewType] with a well-typed [ViewType] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun viewType(viewType: JsonField) = apply { body.viewType(viewType) } + fun viewType(): Optional = viewType.getOptional("view_type") - /** Date of role deletion, or null if the role is still active */ - fun deletedAt(deletedAt: OffsetDateTime?) = apply { body.deletedAt(deletedAt) } + /** + * Date of role deletion, or null if the role is still active + * + * @throws BraintrustInvalidDataException 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") - /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ - fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) + /** + * Options for the view in the app + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun options(): Optional = options.getOptional("options") /** - * Sets [Builder.deletedAt] to an arbitrary JSON value. + * Identifies the user who created the view * - * 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. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun deletedAt(deletedAt: JsonField) = apply { body.deletedAt(deletedAt) } + fun userId(): Optional = userId.getOptional("user_id") - /** Options for the view in the app */ - fun options(options: ViewOptions?) = apply { body.options(options) } + /** + * The view definition + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun viewData(): Optional = viewData.getOptional("view_data") - /** Alias for calling [Builder.options] with `options.orElse(null)`. */ - fun options(options: Optional) = options(options.getOrNull()) + /** + * 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 /** - * Sets [Builder.options] to an arbitrary JSON value. + * Returns the raw JSON value of [objectId]. * - * You should usually call [Builder.options] with a well-typed [ViewOptions] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. */ - fun options(options: JsonField) = apply { body.options(options) } + @JsonProperty("object_id") @ExcludeMissing fun _objectId(): JsonField = objectId - /** Identifies the user who created the view */ - fun userId(userId: String?) = apply { body.userId(userId) } + /** + * Returns the raw JSON value of [objectType]. + * + * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("object_type") + @ExcludeMissing + fun _objectType(): JsonField = objectType - /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ - fun userId(userId: Optional) = userId(userId.getOrNull()) + /** + * Returns the raw JSON value of [viewType]. + * + * Unlike [viewType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("view_type") @ExcludeMissing fun _viewType(): JsonField = viewType /** - * Sets [Builder.userId] to an arbitrary JSON value. + * Returns the raw JSON value of [deletedAt]. * - * 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. + * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. */ - fun userId(userId: JsonField) = apply { body.userId(userId) } + @JsonProperty("deleted_at") + @ExcludeMissing + fun _deletedAt(): JsonField = deletedAt - /** The view definition */ - fun viewData(viewData: ViewData?) = apply { body.viewData(viewData) } + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = options - /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ - fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) + /** + * 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 /** - * Sets [Builder.viewData] to an arbitrary JSON value. + * Returns the raw JSON value of [viewData]. * - * You should usually call [Builder.viewData] with a well-typed [ViewData] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [viewData], this method doesn't throw if the JSON field has an unexpected type. */ - fun viewData(viewData: JsonField) = apply { body.viewData(viewData) } + @JsonProperty("view_data") @ExcludeMissing fun _viewData(): JsonField = viewData - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) + @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 + * .name() + * .objectId() + * .objectType() + * .viewType() + * ``` + */ + @JvmStatic fun builder() = Builder() } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var objectId: JsonField? = null + private var objectType: JsonField? = null + private var viewType: JsonField? = null + private var deletedAt: JsonField = JsonMissing.of() + private var options: JsonField = JsonMissing.of() + private var userId: JsonField = JsonMissing.of() + private var viewData: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + objectId = body.objectId + objectType = body.objectType + viewType = body.viewType + deletedAt = body.deletedAt + options = body.options + userId = body.userId + viewData = body.viewData + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the view */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** The id of the object the view applies to */ + fun objectId(objectId: String) = objectId(JsonField.of(objectId)) + + /** + * Sets [Builder.objectId] to an arbitrary JSON value. + * + * You should usually call [Builder.objectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectId(objectId: JsonField) = apply { this.objectId = objectId } + + /** The object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = objectType(JsonField.of(objectType)) - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) + /** + * Sets [Builder.objectType] to an arbitrary JSON value. + * + * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectType(objectType: JsonField) = apply { + this.objectType = objectType } - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** Type of table that the view corresponds to. */ + fun viewType(viewType: ViewType?) = viewType(JsonField.ofNullable(viewType)) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** Alias for calling [Builder.viewType] with `viewType.orElse(null)`. */ + fun viewType(viewType: Optional) = viewType(viewType.getOrNull()) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Sets [Builder.viewType] to an arbitrary JSON value. + * + * You should usually call [Builder.viewType] with a well-typed [ViewType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun viewType(viewType: JsonField) = apply { this.viewType = viewType } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** Date of role deletion, or null if the role is still active */ + fun deletedAt(deletedAt: OffsetDateTime?) = deletedAt(JsonField.ofNullable(deletedAt)) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ + fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * 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 putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Options for the view in the app */ + fun options(options: ViewOptions?) = options(JsonField.ofNullable(options)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.options] with `options.orElse(null)`. */ + fun options(options: Optional) = options(options.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.options] to an arbitrary JSON value. + * + * You should usually call [Builder.options] with a well-typed [ViewOptions] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun options(options: JsonField) = apply { this.options = options } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** Identifies the user who created the view */ + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * 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 removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + /** The view definition */ + fun viewData(viewData: ViewData?) = viewData(JsonField.ofNullable(viewData)) - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ + fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** + * Sets [Builder.viewData] to an arbitrary JSON value. + * + * You should usually call [Builder.viewData] with a well-typed [ViewData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun viewData(viewData: JsonField) = apply { this.viewData = viewData } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } - - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .objectId() + * .objectType() + * .viewType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("name", name), + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + checkRequired("viewType", viewType), + deletedAt, + options, + userId, + viewData, + additionalProperties.toMutableMap(), + ) } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + private var validated: Boolean = false - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + fun validate(): Body = apply { + if (validated) { + return@apply } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + name() + objectId() + objectType().validate() + viewType().ifPresent { it.validate() } + deletedAt() + options().ifPresent { it.validate() } + userId() + viewData().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + /** - * Returns an immutable instance of [ViewCreateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .objectId() - * .objectType() - * .viewType() - * ``` + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * @throws IllegalStateException if any required field is unset. + * Used for best match union deserialization. */ - fun build(): ViewCreateParams = - ViewCreateParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (viewType.asKnown().getOrNull()?.validity() ?: 0) + + (if (deletedAt.asKnown().isPresent) 1 else 0) + + (options.asKnown().getOrNull()?.validity() ?: 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + (viewData.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && name == other.name && objectId == other.objectId && objectType == other.objectType && viewType == other.viewType && deletedAt == other.deletedAt && options == other.options && userId == other.userId && viewData == other.viewData && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, objectId, objectType, viewType, deletedAt, options, userId, viewData, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, objectId=$objectId, objectType=$objectType, viewType=$viewType, deletedAt=$deletedAt, options=$options, userId=$userId, viewData=$viewData, additionalProperties=$additionalProperties}" } /** Type of table that the view corresponds to. */ @@ -990,6 +1046,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ViewType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewData.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewData.kt index 60697d88..ebc6ae84 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewData.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewData.kt @@ -6,34 +6,33 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 /** The view definition */ -@NoAutoDetect class ViewData -@JsonCreator private constructor( - @JsonProperty("search") - @ExcludeMissing - private val search: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val search: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("search") @ExcludeMissing search: JsonField = JsonMissing.of() + ) : this(search, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun search(): Optional = Optional.ofNullable(search.getNullable("search")) + fun search(): Optional = search.getOptional("search") /** * Returns the raw JSON value of [search]. @@ -42,20 +41,15 @@ private constructor( */ @JsonProperty("search") @ExcludeMissing fun _search(): JsonField = search + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ViewData = apply { - if (validated) { - return@apply - } - - search().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -115,9 +109,35 @@ private constructor( * * Further updates to this [Builder] will not mutate the returned instance. */ - fun build(): ViewData = ViewData(search, additionalProperties.toImmutable()) + fun build(): ViewData = ViewData(search, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): ViewData = apply { + if (validated) { + return@apply + } + + search().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (search.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewDataSearch.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewDataSearch.kt index 35428978..3868ec17 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewDataSearch.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewDataSearch.kt @@ -6,61 +6,62 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 -@NoAutoDetect class ViewDataSearch -@JsonCreator private constructor( - @JsonProperty("filter") - @ExcludeMissing - private val filter: JsonField> = JsonMissing.of(), - @JsonProperty("match") - @ExcludeMissing - private val match: JsonField> = JsonMissing.of(), - @JsonProperty("sort") - @ExcludeMissing - private val sort: JsonField> = JsonMissing.of(), - @JsonProperty("tag") - @ExcludeMissing - private val tag: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val filter: JsonField>, + private val match: JsonField>, + private val sort: JsonField>, + private val tag: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("filter") + @ExcludeMissing + filter: JsonField> = JsonMissing.of(), + @JsonProperty("match") + @ExcludeMissing + match: JsonField> = JsonMissing.of(), + @JsonProperty("sort") @ExcludeMissing sort: JsonField> = JsonMissing.of(), + @JsonProperty("tag") @ExcludeMissing tag: JsonField> = JsonMissing.of(), + ) : this(filter, match, sort, tag, mutableMapOf()) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun filter(): Optional> = Optional.ofNullable(filter.getNullable("filter")) + fun filter(): Optional> = filter.getOptional("filter") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun match(): Optional> = Optional.ofNullable(match.getNullable("match")) + fun match(): Optional> = match.getOptional("match") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun sort(): Optional> = Optional.ofNullable(sort.getNullable("sort")) + fun sort(): Optional> = sort.getOptional("sort") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun tag(): Optional> = Optional.ofNullable(tag.getNullable("tag")) + fun tag(): Optional> = tag.getOptional("tag") /** * Returns the raw JSON value of [filter]. @@ -90,23 +91,15 @@ private constructor( */ @JsonProperty("tag") @ExcludeMissing fun _tag(): JsonField> = tag + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ViewDataSearch = apply { - if (validated) { - return@apply - } - - filter() - match() - sort() - tag() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -274,10 +267,44 @@ private constructor( (match ?: JsonMissing.of()).map { it.toImmutable() }, (sort ?: JsonMissing.of()).map { it.toImmutable() }, (tag ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): ViewDataSearch = apply { + if (validated) { + return@apply + } + + filter() + match() + sort() + tag() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (filter.asKnown().getOrNull()?.sumOf { (if (it == null) 0 else 1).toInt() } ?: 0) + + (match.asKnown().getOrNull()?.sumOf { (if (it == null) 0 else 1).toInt() } ?: 0) + + (sort.asKnown().getOrNull()?.sumOf { (if (it == null) 0 else 1).toInt() } ?: 0) + + (tag.asKnown().getOrNull()?.sumOf { (if (it == null) 0 else 1).toInt() } ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewDeleteParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewDeleteParams.kt index 75878782..4cde6f81 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewDeleteParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewDeleteParams.kt @@ -6,19 +6,18 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 kotlin.jvm.optionals.getOrNull /** Delete a view object by its id */ class ViewDeleteParams @@ -68,195 +67,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> viewId - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * The id of the object the view applies to - * - * @throws BraintrustInvalidDataException 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 objectId(): String = objectId.getRequired("object_id") - - /** - * The object type that the ACL applies to - * - * @throws BraintrustInvalidDataException 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 objectType(): AclObjectType = objectType.getRequired("object_type") - - /** - * Returns the raw JSON value of [objectId]. - * - * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("object_id") @ExcludeMissing fun _objectId(): JsonField = objectId - - /** - * Returns the raw JSON value of [objectType]. - * - * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("object_type") - @ExcludeMissing - fun _objectType(): JsonField = objectType - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - objectId() - objectType() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .objectId() - * .objectType() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var objectId: JsonField? = null - private var objectType: JsonField? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - objectId = body.objectId - objectType = body.objectType - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** The id of the object the view applies to */ - fun objectId(objectId: String) = objectId(JsonField.of(objectId)) - - /** - * Sets [Builder.objectId] to an arbitrary JSON value. - * - * You should usually call [Builder.objectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun objectId(objectId: JsonField) = apply { this.objectId = objectId } - - /** The object type that the ACL applies to */ - fun objectType(objectType: AclObjectType) = objectType(JsonField.of(objectType)) - - /** - * Sets [Builder.objectType] to an arbitrary JSON value. - * - * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun objectType(objectType: JsonField) = apply { - this.objectType = objectType - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.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 - * .objectId() - * .objectType() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("objectId", objectId), - checkRequired("objectType", objectType), - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && objectId == other.objectId && objectType == other.objectType && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(objectId, objectType, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{objectId=$objectId, objectType=$objectType, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @@ -275,7 +85,6 @@ private constructor( } /** A builder for [ViewDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var viewId: String? = null @@ -294,6 +103,16 @@ private constructor( /** View id */ fun viewId(viewId: String) = apply { this.viewId = viewId } + /** + * 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: + * - [objectId] + * - [objectType] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** The id of the object the view applies to */ fun objectId(objectId: String) = apply { body.objectId(objectId) } @@ -457,6 +276,222 @@ private constructor( ) } + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> viewId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val objectId: JsonField, + private val objectType: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("object_id") + @ExcludeMissing + objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + ) : this(objectId, objectType, mutableMapOf()) + + /** + * The id of the object the view applies to + * + * @throws BraintrustInvalidDataException 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 objectId(): String = objectId.getRequired("object_id") + + /** + * The object type that the ACL applies to + * + * @throws BraintrustInvalidDataException 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 objectType(): AclObjectType = objectType.getRequired("object_type") + + /** + * Returns the raw JSON value of [objectId]. + * + * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("object_id") @ExcludeMissing fun _objectId(): JsonField = objectId + + /** + * Returns the raw JSON value of [objectType]. + * + * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("object_type") + @ExcludeMissing + fun _objectType(): JsonField = objectType + + @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 + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var objectId: JsonField? = null + private var objectType: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + objectId = body.objectId + objectType = body.objectType + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** The id of the object the view applies to */ + fun objectId(objectId: String) = objectId(JsonField.of(objectId)) + + /** + * Sets [Builder.objectId] to an arbitrary JSON value. + * + * You should usually call [Builder.objectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectId(objectId: JsonField) = apply { this.objectId = objectId } + + /** The object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = objectType(JsonField.of(objectType)) + + /** + * Sets [Builder.objectType] to an arbitrary JSON value. + * + * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectType(objectType: JsonField) = apply { + this.objectType = objectType + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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 + * .objectId() + * .objectType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + objectId() + objectType().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && objectId == other.objectId && objectType == other.objectType && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objectId, objectType, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{objectId=$objectId, objectType=$objectType, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListPage.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListPage.kt index cd5fd5b9..820ea8ba 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListPage.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListPage.kt @@ -2,161 +2,115 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.blocking.ViewService -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.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.jvm.optionals.getOrNull -/** - * List out all views. The views are sorted by creation date, with the most recently-created views - * coming first - */ +/** @see [ViewService.list] */ class ViewListPage private constructor( - private val viewsService: ViewService, + private val service: ViewService, private val params: ViewListParams, - private val response: Response, + private val response: ViewListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [ViewListPageResponse], but gracefully handles missing data. + * + * @see [ViewListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ViewListPage && viewsService == other.viewsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(viewsService, params, response) /* spotless:on */ - - override fun toString() = - "ViewListPage{viewsService=$viewsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - ViewListParams.builder().from(params).endingBefore(objects().first().id()).build() - ) - } else { - Optional.of( - ViewListParams.builder().from(params).startingAfter(objects().last().id()).build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): Optional { - return getNextPageParams().map { viewsService.list(it) } - } + fun getNextPage(): Optional = getNextPageParams().map { service.list(it) } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(viewsService: ViewService, params: ViewListParams, response: Response) = - ViewListPage(viewsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): ViewListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): ViewListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [ViewListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [ViewListPage]. */ + class Builder internal constructor() { - companion object { + private var service: ViewService? = null + private var params: ViewListParams? = null + private var response: ViewListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [ViewListPage]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(viewListPage: ViewListPage) = apply { + service = viewListPage.service + params = viewListPage.params + response = viewListPage.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: ViewService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: ViewListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ViewListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ViewListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ViewListPage = + ViewListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: ViewListPage) : Iterable { @@ -177,4 +131,16 @@ private constructor( return StreamSupport.stream(spliterator(), false) } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ViewListPage && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = "ViewListPage{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListPageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListPageAsync.kt index e02a4656..c5c6bd0e 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListPageAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListPageAsync.kt @@ -2,163 +2,119 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.ExcludeMissing -import com.braintrustdata.api.core.JsonField -import com.braintrustdata.api.core.JsonMissing -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.services.async.ViewServiceAsync -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.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull -/** - * List out all views. The views are sorted by creation date, with the most recently-created views - * coming first - */ +/** @see [ViewServiceAsync.list] */ class ViewListPageAsync private constructor( - private val viewsService: ViewServiceAsync, + private val service: ViewServiceAsync, private val params: ViewListParams, - private val response: Response, + private val response: ViewListPageResponse, ) { - fun response(): Response = response + /** + * Delegates to [ViewListPageResponse], but gracefully handles missing data. + * + * @see [ViewListPageResponse.objects] + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() - fun objects(): List = response().objects() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ViewListPageAsync && viewsService == other.viewsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(viewsService, params, response) /* spotless:on */ - - override fun toString() = - "ViewListPageAsync{viewsService=$viewsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + fun hasNextPage(): Boolean = objects().isNotEmpty() fun getNextPageParams(): Optional { if (!hasNextPage()) { return Optional.empty() } - return if (params.endingBefore().isPresent) { - Optional.of( - ViewListParams.builder().from(params).endingBefore(objects().first().id()).build() - ) - } else { - Optional.of( - ViewListParams.builder().from(params).startingAfter(objects().last().id()).build() - ) - } + return Optional.of( + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(objects().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(objects().last()._id().getOptional("id")).build() + } + ) } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { viewsService.list(it).thenApply { Optional.of(it) } } + fun getNextPage(): CompletableFuture> = + getNextPageParams() + .map { service.list(it).thenApply { Optional.of(it) } } .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } fun autoPager(): AutoPager = AutoPager(this) - companion object { - - @JvmStatic - fun of(viewsService: ViewServiceAsync, params: ViewListParams, response: Response) = - ViewListPageAsync(viewsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("objects") private val objects: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** The parameters that were used to request this page. */ + fun params(): ViewListParams = params - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The response that this page was parsed from. */ + fun response(): ViewListPageResponse = response - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - objects().map { it.validate() } - validated = true - } + fun toBuilder() = Builder().from(this) - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ - } + companion object { - override fun hashCode(): Int = /* spotless:off */ Objects.hash(objects, additionalProperties) /* spotless:on */ + /** + * Returns a mutable builder for constructing an instance of [ViewListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - override fun toString() = - "Response{objects=$objects, additionalProperties=$additionalProperties}" + /** A builder for [ViewListPageAsync]. */ + class Builder internal constructor() { - companion object { + private var service: ViewServiceAsync? = null + private var params: ViewListParams? = null + private var response: ViewListPageResponse? = null - /** Returns a mutable builder for constructing an instance of [ViewListPageAsync]. */ - @JvmStatic fun builder() = Builder() + @JvmSynthetic + internal fun from(viewListPageAsync: ViewListPageAsync) = apply { + service = viewListPageAsync.service + params = viewListPageAsync.params + response = viewListPageAsync.response } - class Builder { - - private var objects: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.objects = page.objects - this.additionalProperties.putAll(page.additionalProperties) - } - - fun objects(objects: List) = objects(JsonField.of(objects)) - - fun objects(objects: JsonField>) = apply { this.objects = objects } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - /** - * Returns an immutable instance of [Response]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Response = Response(objects, additionalProperties.toImmutable()) - } + fun service(service: ViewServiceAsync) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: ViewListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ViewListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ViewListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ViewListPageAsync = + ViewListPageAsync( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) } class AutoPager(private val firstPage: ViewListPageAsync) { @@ -186,4 +142,17 @@ private constructor( return forEach(values::add, executor).thenApply { values } } } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ViewListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */ + + override fun toString() = + "ViewListPageAsync{service=$service, params=$params, response=$response}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListPageResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListPageResponse.kt new file mode 100644 index 00000000..47ad5868 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListPageResponse.kt @@ -0,0 +1,192 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable +import com.braintrustdata.api.errors.BraintrustInvalidDataException +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 kotlin.jvm.optionals.getOrNull + +class ViewListPageResponse +private constructor( + private val objects: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("objects") @ExcludeMissing objects: JsonField> = JsonMissing.of() + ) : this(objects, mutableMapOf()) + + /** + * A list of view objects + * + * @throws BraintrustInvalidDataException 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 objects(): List = objects.getRequired("objects") + + /** + * Returns the raw JSON value of [objects]. + * + * Unlike [objects], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("objects") @ExcludeMissing fun _objects(): JsonField> = objects + + @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 [ViewListPageResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ViewListPageResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(viewListPageResponse: ViewListPageResponse) = apply { + objects = viewListPageResponse.objects.map { it.toMutableList() } + additionalProperties = viewListPageResponse.additionalProperties.toMutableMap() + } + + /** A list of view objects */ + fun objects(objects: List) = objects(JsonField.of(objects)) + + /** + * Sets [Builder.objects] to an arbitrary JSON value. + * + * You should usually call [Builder.objects] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun objects(objects: JsonField>) = apply { + this.objects = objects.map { it.toMutableList() } + } + + /** + * Adds a single [View] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: View) = apply { + objects = + (objects ?: JsonField.of(mutableListOf())).also { + checkKnown("objects", it).add(object_) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ViewListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objects() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ViewListPageResponse = + ViewListPageResponse( + checkRequired("objects", objects).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ViewListPageResponse = apply { + if (validated) { + return@apply + } + + objects().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (objects.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ViewListPageResponse && objects == other.objects && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ViewListPageResponse{objects=$objects, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListParams.kt index ef2525d5..decac7ce 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListParams.kt @@ -2,23 +2,11 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.getOrThrow import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.errors.BraintrustInvalidDataException -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.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -84,33 +72,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - put("object_id", objectId) - put("object_type", objectType.asString()) - endingBefore?.let { put("ending_before", it) } - ids?.accept( - object : Ids.Visitor { - override fun visitString(string: String) { - put("ids", string) - } - - override fun visitStrings(strings: List) { - put("ids", strings.joinToString(",")) - } - } - ) - limit?.let { put("limit", it.toString()) } - startingAfter?.let { put("starting_after", it) } - viewName?.let { put("view_name", it) } - viewType?.let { put("view_type", it.asString()) } - putAll(additionalQueryParams) - } - .build() - fun toBuilder() = Builder().from(this) companion object { @@ -128,7 +89,6 @@ private constructor( } /** A builder for [ViewListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var objectId: String? = null @@ -353,17 +313,41 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + put("object_id", objectId) + put("object_type", objectType.toString()) + endingBefore?.let { put("ending_before", it) } + ids?.accept( + object : Ids.Visitor { + override fun visitString(string: String) { + put("ids", string) + } + + override fun visitStrings(strings: List) { + put("ids", strings.joinToString(",")) + } + } + ) + limit?.let { put("limit", it.toString()) } + startingAfter?.let { put("starting_after", it) } + viewName?.let { put("view_name", it) } + viewType?.let { put("view_type", it.toString()) } + putAll(additionalQueryParams) + } + .build() + /** * Filter search results to a particular set of object IDs. To specify a list of IDs, include * the query param multiple times */ - @JsonDeserialize(using = Ids.Deserializer::class) - @JsonSerialize(using = Ids.Serializer::class) class Ids private constructor( private val string: String? = null, private val strings: List? = null, - private val _json: JsonValue? = null, ) { fun string(): Optional = Optional.ofNullable(string) @@ -378,15 +362,12 @@ private constructor( fun asStrings(): List = strings.getOrThrow("strings") - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) + else -> throw IllegalStateException("Invalid Ids") } - } override fun equals(other: Any?): Boolean { if (this === other) { @@ -402,7 +383,6 @@ private constructor( when { string != null -> "Ids{string=$string}" strings != null -> "Ids{strings=$strings}" - _json != null -> "Ids{_unknown=$_json}" else -> throw IllegalStateException("Invalid Ids") } @@ -419,51 +399,6 @@ private constructor( fun visitString(string: String): T fun visitStrings(strings: List): T - - /** - * Maps an unknown variant of [Ids] to a value of type [T]. - * - * An instance of [Ids] 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 BraintrustInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Ids: $json") - } - } - - internal class Deserializer : BaseDeserializer(Ids::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Ids { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Ids(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Ids(strings = it, _json = json) - } - - return Ids(_json = json) - } - } - - internal class Serializer : BaseSerializer(Ids::class) { - - override fun serialize( - value: Ids, - 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 Ids") - } - } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewOptions.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewOptions.kt index bf4af30f..2a50e44b 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewOptions.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewOptions.kt @@ -6,83 +6,90 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.checkKnown -import com.braintrustdata.api.core.immutableEmptyMap import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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 /** Options for the view in the app */ -@NoAutoDetect class ViewOptions -@JsonCreator private constructor( - @JsonProperty("columnOrder") - @ExcludeMissing - private val columnOrder: JsonField> = JsonMissing.of(), - @JsonProperty("columnSizing") - @ExcludeMissing - private val columnSizing: JsonField = JsonMissing.of(), - @JsonProperty("columnVisibility") - @ExcludeMissing - private val columnVisibility: JsonField = JsonMissing.of(), - @JsonProperty("grouping") - @ExcludeMissing - private val grouping: JsonField = JsonMissing.of(), - @JsonProperty("layout") - @ExcludeMissing - private val layout: JsonField = JsonMissing.of(), - @JsonProperty("rowHeight") - @ExcludeMissing - private val rowHeight: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val columnOrder: JsonField>, + private val columnSizing: JsonField, + private val columnVisibility: JsonField, + private val grouping: JsonField, + private val layout: JsonField, + private val rowHeight: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("columnOrder") + @ExcludeMissing + columnOrder: JsonField> = JsonMissing.of(), + @JsonProperty("columnSizing") + @ExcludeMissing + columnSizing: JsonField = JsonMissing.of(), + @JsonProperty("columnVisibility") + @ExcludeMissing + columnVisibility: JsonField = JsonMissing.of(), + @JsonProperty("grouping") @ExcludeMissing grouping: JsonField = JsonMissing.of(), + @JsonProperty("layout") @ExcludeMissing layout: JsonField = JsonMissing.of(), + @JsonProperty("rowHeight") @ExcludeMissing rowHeight: JsonField = JsonMissing.of(), + ) : this( + columnOrder, + columnSizing, + columnVisibility, + grouping, + layout, + rowHeight, + mutableMapOf(), + ) + /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun columnOrder(): Optional> = - Optional.ofNullable(columnOrder.getNullable("columnOrder")) + fun columnOrder(): Optional> = columnOrder.getOptional("columnOrder") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun columnSizing(): Optional = - Optional.ofNullable(columnSizing.getNullable("columnSizing")) + fun columnSizing(): Optional = columnSizing.getOptional("columnSizing") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun columnVisibility(): Optional = - Optional.ofNullable(columnVisibility.getNullable("columnVisibility")) + columnVisibility.getOptional("columnVisibility") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun grouping(): Optional = Optional.ofNullable(grouping.getNullable("grouping")) + fun grouping(): Optional = grouping.getOptional("grouping") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun layout(): Optional = Optional.ofNullable(layout.getNullable("layout")) + fun layout(): Optional = layout.getOptional("layout") /** * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun rowHeight(): Optional = Optional.ofNullable(rowHeight.getNullable("rowHeight")) + fun rowHeight(): Optional = rowHeight.getOptional("rowHeight") /** * Returns the raw JSON value of [columnOrder]. @@ -133,25 +140,15 @@ private constructor( */ @JsonProperty("rowHeight") @ExcludeMissing fun _rowHeight(): JsonField = rowHeight + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ViewOptions = apply { - if (validated) { - return@apply - } - - columnOrder() - columnSizing().ifPresent { it.validate() } - columnVisibility().ifPresent { it.validate() } - grouping() - layout() - rowHeight() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) @@ -319,32 +316,59 @@ private constructor( grouping, layout, rowHeight, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): ViewOptions = apply { + if (validated) { + return@apply + } + + columnOrder() + columnSizing().ifPresent { it.validate() } + columnVisibility().ifPresent { it.validate() } + grouping() + layout() + rowHeight() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (columnOrder.asKnown().getOrNull()?.size ?: 0) + + (columnSizing.asKnown().getOrNull()?.validity() ?: 0) + + (columnVisibility.asKnown().getOrNull()?.validity() ?: 0) + + (if (grouping.asKnown().isPresent) 1 else 0) + + (if (layout.asKnown().isPresent) 1 else 0) + + (if (rowHeight.asKnown().isPresent) 1 else 0) + class ColumnSizing @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): ColumnSizing = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -390,6 +414,34 @@ private constructor( fun build(): ColumnSizing = ColumnSizing(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): ColumnSizing = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 @@ -407,28 +459,17 @@ private constructor( override fun toString() = "ColumnSizing{additionalProperties=$additionalProperties}" } - @NoAutoDetect class ColumnVisibility @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): ColumnVisibility = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { @@ -474,6 +515,34 @@ private constructor( fun build(): ColumnVisibility = ColumnVisibility(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): ColumnVisibility = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewReplaceParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewReplaceParams.kt index 8f84c8c9..1f5303d5 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewReplaceParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewReplaceParams.kt @@ -7,19 +7,17 @@ import com.braintrustdata.api.core.ExcludeMissing import com.braintrustdata.api.core.JsonField import com.braintrustdata.api.core.JsonMissing import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.QueryParams -import com.braintrustdata.api.core.immutableEmptyMap -import com.braintrustdata.api.core.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException 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.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -161,422 +159,281 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + fun toBuilder() = Builder().from(this) - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("view_type") - @ExcludeMissing - private val viewType: JsonField = JsonMissing.of(), - @JsonProperty("deleted_at") - @ExcludeMissing - private val deletedAt: JsonField = JsonMissing.of(), - @JsonProperty("options") - @ExcludeMissing - private val options: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonProperty("view_data") - @ExcludeMissing - private val viewData: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + companion object { /** - * Name of the view + * Returns a mutable builder for constructing an instance of [ViewReplaceParams]. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * The following fields are required: + * ```java + * .name() + * .objectId() + * .objectType() + * .viewType() + * ``` */ - fun name(): String = name.getRequired("name") + @JvmStatic fun builder() = Builder() + } - /** - * The id of the object the view applies to - * - * @throws BraintrustInvalidDataException 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 objectId(): String = objectId.getRequired("object_id") + /** A builder for [ViewReplaceParams]. */ + class Builder internal constructor() { - /** - * The object type that the ACL applies to - * - * @throws BraintrustInvalidDataException 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 objectType(): AclObjectType = objectType.getRequired("object_type") + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - /** - * Type of table that the view corresponds to. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun viewType(): Optional = Optional.ofNullable(viewType.getNullable("view_type")) + @JvmSynthetic + internal fun from(viewReplaceParams: ViewReplaceParams) = apply { + body = viewReplaceParams.body.toBuilder() + additionalHeaders = viewReplaceParams.additionalHeaders.toBuilder() + additionalQueryParams = viewReplaceParams.additionalQueryParams.toBuilder() + } /** - * Date of role deletion, or null if the role is still active + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * 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: + * - [name] + * - [objectId] + * - [objectType] + * - [viewType] + * - [deletedAt] + * - etc. */ - fun deletedAt(): Optional = - Optional.ofNullable(deletedAt.getNullable("deleted_at")) + fun body(body: Body) = apply { this.body = body.toBuilder() } - /** - * Options for the view in the app - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun options(): Optional = Optional.ofNullable(options.getNullable("options")) + /** Name of the view */ + fun name(name: String) = apply { body.name(name) } /** - * Identifies the user who created the view + * Sets [Builder.name] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected 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 userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) + fun name(name: JsonField) = apply { body.name(name) } - /** - * The view definition - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun viewData(): Optional = Optional.ofNullable(viewData.getNullable("view_data")) + /** The id of the object the view applies to */ + fun objectId(objectId: String) = apply { body.objectId(objectId) } /** - * Returns the raw JSON value of [name]. + * Sets [Builder.objectId] to an arbitrary JSON value. * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.objectId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + fun objectId(objectId: JsonField) = apply { body.objectId(objectId) } - /** - * Returns the raw JSON value of [objectId]. - * - * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("object_id") @ExcludeMissing fun _objectId(): JsonField = objectId + /** The object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = apply { body.objectType(objectType) } /** - * Returns the raw JSON value of [objectType]. + * Sets [Builder.objectType] to an arbitrary JSON value. * - * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @JsonProperty("object_type") - @ExcludeMissing - fun _objectType(): JsonField = objectType + fun objectType(objectType: JsonField) = apply { body.objectType(objectType) } - /** - * Returns the raw JSON value of [viewType]. - * - * Unlike [viewType], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("view_type") @ExcludeMissing fun _viewType(): JsonField = viewType + /** Type of table that the view corresponds to. */ + fun viewType(viewType: ViewType?) = apply { body.viewType(viewType) } + + /** Alias for calling [Builder.viewType] with `viewType.orElse(null)`. */ + fun viewType(viewType: Optional) = viewType(viewType.getOrNull()) /** - * Returns the raw JSON value of [deletedAt]. + * Sets [Builder.viewType] to an arbitrary JSON value. * - * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.viewType] with a well-typed [ViewType] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("deleted_at") - @ExcludeMissing - fun _deletedAt(): JsonField = deletedAt + fun viewType(viewType: JsonField) = apply { body.viewType(viewType) } + + /** Date of role deletion, or null if the role is still active */ + fun deletedAt(deletedAt: OffsetDateTime?) = apply { body.deletedAt(deletedAt) } + + /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ + fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) /** - * Returns the raw JSON value of [options]. + * Sets [Builder.deletedAt] to an arbitrary JSON value. * - * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = options + fun deletedAt(deletedAt: JsonField) = apply { body.deletedAt(deletedAt) } + + /** Options for the view in the app */ + fun options(options: ViewOptions?) = apply { body.options(options) } + + /** Alias for calling [Builder.options] with `options.orElse(null)`. */ + fun options(options: Optional) = options(options.getOrNull()) /** - * Returns the raw JSON value of [userId]. + * Sets [Builder.options] to an arbitrary JSON value. * - * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.options] with a well-typed [ViewOptions] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + fun options(options: JsonField) = apply { body.options(options) } + + /** Identifies the user who created the view */ + fun userId(userId: String?) = apply { body.userId(userId) } + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) /** - * Returns the raw JSON value of [viewData]. + * Sets [Builder.userId] to an arbitrary JSON value. * - * Unlike [viewData], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("view_data") @ExcludeMissing fun _viewData(): JsonField = viewData + fun userId(userId: JsonField) = apply { body.userId(userId) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** The view definition */ + fun viewData(viewData: ViewData?) = apply { body.viewData(viewData) } - private var validated: Boolean = false + /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ + fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) - fun validate(): Body = apply { - if (validated) { - return@apply - } + /** + * Sets [Builder.viewData] to an arbitrary JSON value. + * + * You should usually call [Builder.viewData] with a well-typed [ViewData] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun viewData(viewData: JsonField) = apply { body.viewData(viewData) } - name() - objectId() - objectType() - viewType() - deletedAt() - options().ifPresent { it.validate() } - userId() - viewData().ifPresent { it.validate() } - validated = true + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) } - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .name() - * .objectId() - * .objectType() - * .viewType() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) } - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var name: JsonField? = null - private var objectId: JsonField? = null - private var objectType: JsonField? = null - private var viewType: JsonField? = null - private var deletedAt: JsonField = JsonMissing.of() - private var options: JsonField = JsonMissing.of() - private var userId: JsonField = JsonMissing.of() - private var viewData: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - name = body.name - objectId = body.objectId - objectType = body.objectType - viewType = body.viewType - deletedAt = body.deletedAt - options = body.options - userId = body.userId - viewData = body.viewData - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** Name of the view */ - fun name(name: String) = name(JsonField.of(name)) - - /** - * Sets [Builder.name] to an arbitrary JSON value. - * - * You should usually call [Builder.name] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun name(name: JsonField) = apply { this.name = name } - - /** The id of the object the view applies to */ - fun objectId(objectId: String) = objectId(JsonField.of(objectId)) - - /** - * Sets [Builder.objectId] to an arbitrary JSON value. - * - * You should usually call [Builder.objectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun objectId(objectId: JsonField) = apply { this.objectId = objectId } - - /** The object type that the ACL applies to */ - fun objectType(objectType: AclObjectType) = objectType(JsonField.of(objectType)) - - /** - * Sets [Builder.objectType] to an arbitrary JSON value. - * - * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun objectType(objectType: JsonField) = apply { - this.objectType = objectType + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - /** Type of table that the view corresponds to. */ - fun viewType(viewType: ViewType?) = viewType(JsonField.ofNullable(viewType)) - - /** Alias for calling [Builder.viewType] with `viewType.orElse(null)`. */ - fun viewType(viewType: Optional) = viewType(viewType.getOrNull()) - - /** - * Sets [Builder.viewType] to an arbitrary JSON value. - * - * You should usually call [Builder.viewType] with a well-typed [ViewType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun viewType(viewType: JsonField) = apply { this.viewType = viewType } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - /** Date of role deletion, or null if the role is still active */ - fun deletedAt(deletedAt: OffsetDateTime?) = deletedAt(JsonField.ofNullable(deletedAt)) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ - fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * 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 additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Options for the view in the app */ - fun options(options: ViewOptions?) = options(JsonField.ofNullable(options)) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** Alias for calling [Builder.options] with `options.orElse(null)`. */ - fun options(options: Optional) = options(options.getOrNull()) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** - * Sets [Builder.options] to an arbitrary JSON value. - * - * You should usually call [Builder.options] with a well-typed [ViewOptions] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun options(options: JsonField) = apply { this.options = options } + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Identifies the user who created the view */ - fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ - fun userId(userId: Optional) = userId(userId.getOrNull()) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * 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 replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** The view definition */ - fun viewData(viewData: ViewData?) = viewData(JsonField.ofNullable(viewData)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ - fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.viewData] to an arbitrary JSON value. - * - * You should usually call [Builder.viewData] with a well-typed [ViewData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun viewData(viewData: JsonField) = apply { this.viewData = viewData } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .name() - * .objectId() - * .objectType() - * .viewType() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("name", name), - checkRequired("objectId", objectId), - checkRequired("objectType", objectType), - checkRequired("viewType", viewType), - deletedAt, - options, - userId, - viewData, - additionalProperties.toImmutable(), - ) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && name == other.name && objectId == other.objectId && objectType == other.objectType && viewType == other.viewType && deletedAt == other.deletedAt && options == other.options && userId == other.userId && viewData == other.viewData && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, objectId, objectType, viewType, deletedAt, options, userId, viewData, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{name=$name, objectId=$objectId, objectType=$objectType, viewType=$viewType, deletedAt=$deletedAt, options=$options, userId=$userId, viewData=$viewData, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [ViewReplaceParams]. + * Returns an immutable instance of [ViewReplaceParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java @@ -585,271 +442,470 @@ private constructor( * .objectType() * .viewType() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): ViewReplaceParams = + ViewReplaceParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [ViewReplaceParams]. */ - @NoAutoDetect - class Builder internal constructor() { + fun _body(): Body = body - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + override fun _headers(): Headers = additionalHeaders - @JvmSynthetic - internal fun from(viewReplaceParams: ViewReplaceParams) = apply { - body = viewReplaceParams.body.toBuilder() - additionalHeaders = viewReplaceParams.additionalHeaders.toBuilder() - additionalQueryParams = viewReplaceParams.additionalQueryParams.toBuilder() - } + override fun _queryParams(): QueryParams = additionalQueryParams - /** Name of the view */ - fun name(name: String) = apply { body.name(name) } + class Body + private constructor( + private val name: JsonField, + private val objectId: JsonField, + private val objectType: JsonField, + private val viewType: JsonField, + private val deletedAt: JsonField, + private val options: JsonField, + private val userId: JsonField, + private val viewData: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("object_id") + @ExcludeMissing + objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("view_type") + @ExcludeMissing + viewType: JsonField = JsonMissing.of(), + @JsonProperty("deleted_at") + @ExcludeMissing + deletedAt: JsonField = JsonMissing.of(), + @JsonProperty("options") + @ExcludeMissing + options: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + @JsonProperty("view_data") + @ExcludeMissing + viewData: JsonField = JsonMissing.of(), + ) : this( + name, + objectId, + objectType, + viewType, + deletedAt, + options, + userId, + viewData, + mutableMapOf(), + ) /** - * Sets [Builder.name] to an arbitrary JSON value. + * Name of the view * - * 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. + * @throws BraintrustInvalidDataException 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(name: JsonField) = apply { body.name(name) } - - /** The id of the object the view applies to */ - fun objectId(objectId: String) = apply { body.objectId(objectId) } + fun name(): String = name.getRequired("name") /** - * Sets [Builder.objectId] to an arbitrary JSON value. + * The id of the object the view applies to * - * You should usually call [Builder.objectId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException 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 objectId(objectId: JsonField) = apply { body.objectId(objectId) } - - /** The object type that the ACL applies to */ - fun objectType(objectType: AclObjectType) = apply { body.objectType(objectType) } + fun objectId(): String = objectId.getRequired("object_id") /** - * Sets [Builder.objectType] to an arbitrary JSON value. + * The object type that the ACL applies to * - * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException 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 objectType(objectType: JsonField) = apply { body.objectType(objectType) } - - /** Type of table that the view corresponds to. */ - fun viewType(viewType: ViewType?) = apply { body.viewType(viewType) } - - /** Alias for calling [Builder.viewType] with `viewType.orElse(null)`. */ - fun viewType(viewType: Optional) = viewType(viewType.getOrNull()) + fun objectType(): AclObjectType = objectType.getRequired("object_type") /** - * Sets [Builder.viewType] to an arbitrary JSON value. + * Type of table that the view corresponds to. * - * You should usually call [Builder.viewType] with a well-typed [ViewType] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun viewType(viewType: JsonField) = apply { body.viewType(viewType) } + fun viewType(): Optional = viewType.getOptional("view_type") - /** Date of role deletion, or null if the role is still active */ - fun deletedAt(deletedAt: OffsetDateTime?) = apply { body.deletedAt(deletedAt) } + /** + * Date of role deletion, or null if the role is still active + * + * @throws BraintrustInvalidDataException 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") - /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ - fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) + /** + * Options for the view in the app + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun options(): Optional = options.getOptional("options") /** - * Sets [Builder.deletedAt] to an arbitrary JSON value. + * Identifies the user who created the view * - * 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. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun deletedAt(deletedAt: JsonField) = apply { body.deletedAt(deletedAt) } + fun userId(): Optional = userId.getOptional("user_id") - /** Options for the view in the app */ - fun options(options: ViewOptions?) = apply { body.options(options) } + /** + * The view definition + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun viewData(): Optional = viewData.getOptional("view_data") - /** Alias for calling [Builder.options] with `options.orElse(null)`. */ - fun options(options: Optional) = options(options.getOrNull()) + /** + * 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 /** - * Sets [Builder.options] to an arbitrary JSON value. + * Returns the raw JSON value of [objectId]. * - * You should usually call [Builder.options] with a well-typed [ViewOptions] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. */ - fun options(options: JsonField) = apply { body.options(options) } + @JsonProperty("object_id") @ExcludeMissing fun _objectId(): JsonField = objectId - /** Identifies the user who created the view */ - fun userId(userId: String?) = apply { body.userId(userId) } + /** + * Returns the raw JSON value of [objectType]. + * + * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("object_type") + @ExcludeMissing + fun _objectType(): JsonField = objectType - /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ - fun userId(userId: Optional) = userId(userId.getOrNull()) + /** + * Returns the raw JSON value of [viewType]. + * + * Unlike [viewType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("view_type") @ExcludeMissing fun _viewType(): JsonField = viewType /** - * Sets [Builder.userId] to an arbitrary JSON value. + * Returns the raw JSON value of [deletedAt]. * - * 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. + * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. */ - fun userId(userId: JsonField) = apply { body.userId(userId) } + @JsonProperty("deleted_at") + @ExcludeMissing + fun _deletedAt(): JsonField = deletedAt - /** The view definition */ - fun viewData(viewData: ViewData?) = apply { body.viewData(viewData) } + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = options - /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ - fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) + /** + * 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 /** - * Sets [Builder.viewData] to an arbitrary JSON value. + * Returns the raw JSON value of [viewData]. * - * You should usually call [Builder.viewData] with a well-typed [ViewData] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [viewData], this method doesn't throw if the JSON field has an unexpected type. */ - fun viewData(viewData: JsonField) = apply { body.viewData(viewData) } + @JsonProperty("view_data") @ExcludeMissing fun _viewData(): JsonField = viewData - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(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 + * .name() + * .objectId() + * .objectType() + * .viewType() + * ``` + */ + @JvmStatic fun builder() = Builder() } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var objectId: JsonField? = null + private var objectType: JsonField? = null + private var viewType: JsonField? = null + private var deletedAt: JsonField = JsonMissing.of() + private var options: JsonField = JsonMissing.of() + private var userId: JsonField = JsonMissing.of() + private var viewData: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + objectId = body.objectId + objectType = body.objectType + viewType = body.viewType + deletedAt = body.deletedAt + options = body.options + userId = body.userId + viewData = body.viewData + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the view */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** The id of the object the view applies to */ + fun objectId(objectId: String) = objectId(JsonField.of(objectId)) + + /** + * Sets [Builder.objectId] to an arbitrary JSON value. + * + * You should usually call [Builder.objectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectId(objectId: JsonField) = apply { this.objectId = objectId } + + /** The object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = objectType(JsonField.of(objectType)) + + /** + * Sets [Builder.objectType] to an arbitrary JSON value. + * + * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectType(objectType: JsonField) = apply { + this.objectType = objectType } - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** Type of table that the view corresponds to. */ + fun viewType(viewType: ViewType?) = viewType(JsonField.ofNullable(viewType)) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** Alias for calling [Builder.viewType] with `viewType.orElse(null)`. */ + fun viewType(viewType: Optional) = viewType(viewType.getOrNull()) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Sets [Builder.viewType] to an arbitrary JSON value. + * + * You should usually call [Builder.viewType] with a well-typed [ViewType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun viewType(viewType: JsonField) = apply { this.viewType = viewType } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** Date of role deletion, or null if the role is still active */ + fun deletedAt(deletedAt: OffsetDateTime?) = deletedAt(JsonField.ofNullable(deletedAt)) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ + fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * 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 putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Options for the view in the app */ + fun options(options: ViewOptions?) = options(JsonField.ofNullable(options)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.options] with `options.orElse(null)`. */ + fun options(options: Optional) = options(options.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.options] to an arbitrary JSON value. + * + * You should usually call [Builder.options] with a well-typed [ViewOptions] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun options(options: JsonField) = apply { this.options = options } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** Identifies the user who created the view */ + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * 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 removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + /** The view definition */ + fun viewData(viewData: ViewData?) = viewData(JsonField.ofNullable(viewData)) - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ + fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** + * Sets [Builder.viewData] to an arbitrary JSON value. + * + * You should usually call [Builder.viewData] with a well-typed [ViewData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun viewData(viewData: JsonField) = apply { this.viewData = viewData } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } - - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .objectId() + * .objectType() + * .viewType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("name", name), + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + checkRequired("viewType", viewType), + deletedAt, + options, + userId, + viewData, + additionalProperties.toMutableMap(), + ) } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + private var validated: Boolean = false - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + fun validate(): Body = apply { + if (validated) { + return@apply } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + name() + objectId() + objectType().validate() + viewType().ifPresent { it.validate() } + deletedAt() + options().ifPresent { it.validate() } + userId() + viewData().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + /** - * Returns an immutable instance of [ViewReplaceParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * The following fields are required: - * ```java - * .name() - * .objectId() - * .objectType() - * .viewType() - * ``` - * - * @throws IllegalStateException if any required field is unset. + * Used for best match union deserialization. */ - fun build(): ViewReplaceParams = - ViewReplaceParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (viewType.asKnown().getOrNull()?.validity() ?: 0) + + (if (deletedAt.asKnown().isPresent) 1 else 0) + + (options.asKnown().getOrNull()?.validity() ?: 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + (viewData.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && name == other.name && objectId == other.objectId && objectType == other.objectType && viewType == other.viewType && deletedAt == other.deletedAt && options == other.options && userId == other.userId && viewData == other.viewData && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(name, objectId, objectType, viewType, deletedAt, options, userId, viewData, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, objectId=$objectId, objectType=$objectType, viewType=$viewType, deletedAt=$deletedAt, options=$options, userId=$userId, viewData=$viewData, additionalProperties=$additionalProperties}" } /** Type of table that the view corresponds to. */ @@ -994,6 +1050,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ViewType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewRetrieveParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewRetrieveParams.kt index 0e6067a2..7f27c2a4 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewRetrieveParams.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewRetrieveParams.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect import com.braintrustdata.api.core.Params import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.core.http.Headers @@ -32,24 +31,6 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - put("object_id", objectId) - put("object_type", objectType.asString()) - putAll(additionalQueryParams) - } - .build() - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> viewId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { @@ -68,7 +49,6 @@ private constructor( } /** A builder for [ViewRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var viewId: String? = null @@ -217,6 +197,23 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> viewId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + put("object_id", objectId) + put("object_type", objectType.toString()) + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewType.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewType.kt index f09a7f19..9f8db16f 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewType.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewType.kt @@ -146,6 +146,32 @@ class ViewType @JsonCreator private constructor(private val value: JsonField viewId - else -> "" + /** A builder for [ViewUpdateParams]. */ + class Builder internal constructor() { + + private var viewId: 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(viewUpdateParams: ViewUpdateParams) = apply { + viewId = viewUpdateParams.viewId + body = viewUpdateParams.body.toBuilder() + additionalHeaders = viewUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = viewUpdateParams.additionalQueryParams.toBuilder() } - } - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("object_id") - @ExcludeMissing - private val objectId: JsonField = JsonMissing.of(), - @JsonProperty("object_type") - @ExcludeMissing - private val objectType: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("options") - @ExcludeMissing - private val options: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonProperty("view_data") - @ExcludeMissing - private val viewData: JsonField = JsonMissing.of(), - @JsonProperty("view_type") - @ExcludeMissing - private val viewType: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** View id */ + fun viewId(viewId: String) = apply { this.viewId = viewId } /** - * The id of the object the view applies to + * Sets the entire request body. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * 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: + * - [objectId] + * - [objectType] + * - [name] + * - [options] + * - [userId] + * - etc. */ - fun objectId(): String = objectId.getRequired("object_id") + fun body(body: Body) = apply { this.body = body.toBuilder() } - /** - * The object type that the ACL applies to - * - * @throws BraintrustInvalidDataException 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 objectType(): AclObjectType = objectType.getRequired("object_type") + /** The id of the object the view applies to */ + fun objectId(objectId: String) = apply { body.objectId(objectId) } /** - * Name of the view + * Sets [Builder.objectId] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.objectId] 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(): Optional = Optional.ofNullable(name.getNullable("name")) + fun objectId(objectId: JsonField) = apply { body.objectId(objectId) } - /** - * Options for the view in the app - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun options(): Optional = Optional.ofNullable(options.getNullable("options")) + /** The object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = apply { body.objectType(objectType) } /** - * Identifies the user who created the view + * Sets [Builder.objectType] to an arbitrary JSON value. * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) + fun objectType(objectType: JsonField) = apply { body.objectType(objectType) } - /** - * The view definition - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun viewData(): Optional = Optional.ofNullable(viewData.getNullable("view_data")) + /** Name of the view */ + fun name(name: String?) = apply { body.name(name) } - /** - * Type of table that the view corresponds to. - * - * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). - */ - fun viewType(): Optional = Optional.ofNullable(viewType.getNullable("view_type")) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) /** - * Returns the raw JSON value of [objectId]. + * Sets [Builder.name] to an arbitrary JSON value. * - * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("object_id") @ExcludeMissing fun _objectId(): JsonField = objectId + fun name(name: JsonField) = apply { body.name(name) } - /** - * Returns the raw JSON value of [objectType]. - * - * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("object_type") - @ExcludeMissing - fun _objectType(): JsonField = objectType + /** Options for the view in the app */ + fun options(options: ViewOptions?) = apply { body.options(options) } - /** - * 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 + /** Alias for calling [Builder.options] with `options.orElse(null)`. */ + fun options(options: Optional) = options(options.getOrNull()) /** - * Returns the raw JSON value of [options]. + * Sets [Builder.options] to an arbitrary JSON value. * - * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.options] with a well-typed [ViewOptions] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = options + fun options(options: JsonField) = apply { body.options(options) } - /** - * 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 + /** Identifies the user who created the view */ + fun userId(userId: String?) = apply { body.userId(userId) } + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) /** - * Returns the raw JSON value of [viewData]. + * Sets [Builder.userId] to an arbitrary JSON value. * - * Unlike [viewData], this method doesn't throw if the JSON field has an unexpected type. + * 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. */ - @JsonProperty("view_data") @ExcludeMissing fun _viewData(): JsonField = viewData + fun userId(userId: JsonField) = apply { body.userId(userId) } + + /** The view definition */ + fun viewData(viewData: ViewData?) = apply { body.viewData(viewData) } + + /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ + fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) /** - * Returns the raw JSON value of [viewType]. + * Sets [Builder.viewData] to an arbitrary JSON value. * - * Unlike [viewType], this method doesn't throw if the JSON field has an unexpected type. + * You should usually call [Builder.viewData] with a well-typed [ViewData] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - @JsonProperty("view_type") @ExcludeMissing fun _viewType(): JsonField = viewType + fun viewData(viewData: JsonField) = apply { body.viewData(viewData) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** Type of table that the view corresponds to. */ + fun viewType(viewType: ViewType?) = apply { body.viewType(viewType) } - private var validated: Boolean = false + /** Alias for calling [Builder.viewType] with `viewType.orElse(null)`. */ + fun viewType(viewType: Optional) = viewType(viewType.getOrNull()) - fun validate(): Body = apply { - if (validated) { - return@apply - } + /** + * Sets [Builder.viewType] to an arbitrary JSON value. + * + * You should usually call [Builder.viewType] with a well-typed [ViewType] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun viewType(viewType: JsonField) = apply { body.viewType(viewType) } - objectId() - objectType() - name() - options().ifPresent { it.validate() } - userId() - viewData().ifPresent { it.validate() } - viewType() - validated = true + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) } - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .objectId() - * .objectType() - * ``` - */ - @JvmStatic fun builder() = Builder() + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) } - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var objectId: JsonField? = null - private var objectType: JsonField? = null - private var name: JsonField = JsonMissing.of() - private var options: JsonField = JsonMissing.of() - private var userId: JsonField = JsonMissing.of() - private var viewData: JsonField = JsonMissing.of() - private var viewType: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - objectId = body.objectId - objectType = body.objectType - name = body.name - options = body.options - userId = body.userId - viewData = body.viewData - viewType = body.viewType - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** The id of the object the view applies to */ - fun objectId(objectId: String) = objectId(JsonField.of(objectId)) - - /** - * Sets [Builder.objectId] to an arbitrary JSON value. - * - * You should usually call [Builder.objectId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun objectId(objectId: JsonField) = apply { this.objectId = objectId } - - /** The object type that the ACL applies to */ - fun objectType(objectType: AclObjectType) = objectType(JsonField.of(objectType)) - - /** - * Sets [Builder.objectType] to an arbitrary JSON value. - * - * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun objectType(objectType: JsonField) = apply { - this.objectType = objectType + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - /** Name of the view */ - 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 } - - /** Options for the view in the app */ - fun options(options: ViewOptions?) = options(JsonField.ofNullable(options)) + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - /** Alias for calling [Builder.options] with `options.orElse(null)`. */ - fun options(options: Optional) = options(options.getOrNull()) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** - * Sets [Builder.options] to an arbitrary JSON value. - * - * You should usually call [Builder.options] with a well-typed [ViewOptions] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun options(options: JsonField) = apply { this.options = options } + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Identifies the user who created the view */ - fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ - fun userId(userId: Optional) = userId(userId.getOrNull()) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** - * 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 putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** The view definition */ - fun viewData(viewData: ViewData?) = viewData(JsonField.ofNullable(viewData)) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ - fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** - * Sets [Builder.viewData] to an arbitrary JSON value. - * - * You should usually call [Builder.viewData] with a well-typed [ViewData] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun viewData(viewData: JsonField) = apply { this.viewData = viewData } + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** Type of table that the view corresponds to. */ - fun viewType(viewType: ViewType?) = viewType(JsonField.ofNullable(viewType)) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** Alias for calling [Builder.viewType] with `viewType.orElse(null)`. */ - fun viewType(viewType: Optional) = viewType(viewType.getOrNull()) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * Sets [Builder.viewType] to an arbitrary JSON value. - * - * You should usually call [Builder.viewType] with a well-typed [ViewType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun viewType(viewType: JsonField) = apply { this.viewType = viewType } + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .objectId() - * .objectType() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("objectId", objectId), - checkRequired("objectType", objectType), - name, - options, - userId, - viewData, - viewType, - additionalProperties.toImmutable(), - ) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - return /* spotless:off */ other is Body && objectId == other.objectId && objectType == other.objectType && name == other.name && options == other.options && userId == other.userId && viewData == other.viewData && viewType == other.viewType && additionalProperties == other.additionalProperties /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(objectId, objectType, name, options, userId, viewData, viewType, additionalProperties) } - /* spotless:on */ + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - override fun hashCode(): Int = hashCode + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - override fun toString() = - "Body{objectId=$objectId, objectType=$objectType, name=$name, options=$options, userId=$userId, viewData=$viewData, viewType=$viewType, additionalProperties=$additionalProperties}" - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - companion object { + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } /** - * Returns a mutable builder for constructing an instance of [ViewUpdateParams]. + * Returns an immutable instance of [ViewUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. * * The following fields are required: * ```java @@ -537,264 +422,423 @@ private constructor( * .objectId() * .objectType() * ``` + * + * @throws IllegalStateException if any required field is unset. */ - @JvmStatic fun builder() = Builder() + fun build(): ViewUpdateParams = + ViewUpdateParams( + checkRequired("viewId", viewId), + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - /** A builder for [ViewUpdateParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var viewId: String? = null - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + fun _body(): Body = body - @JvmSynthetic - internal fun from(viewUpdateParams: ViewUpdateParams) = apply { - viewId = viewUpdateParams.viewId - body = viewUpdateParams.body.toBuilder() - additionalHeaders = viewUpdateParams.additionalHeaders.toBuilder() - additionalQueryParams = viewUpdateParams.additionalQueryParams.toBuilder() + fun _pathParam(index: Int): String = + when (index) { + 0 -> viewId + else -> "" } - /** View id */ - fun viewId(viewId: String) = apply { this.viewId = viewId } + override fun _headers(): Headers = additionalHeaders - /** The id of the object the view applies to */ - fun objectId(objectId: String) = apply { body.objectId(objectId) } + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val objectId: JsonField, + private val objectType: JsonField, + private val name: JsonField, + private val options: JsonField, + private val userId: JsonField, + private val viewData: JsonField, + private val viewType: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("object_id") + @ExcludeMissing + objectId: JsonField = JsonMissing.of(), + @JsonProperty("object_type") + @ExcludeMissing + objectType: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("options") + @ExcludeMissing + options: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + @JsonProperty("view_data") + @ExcludeMissing + viewData: JsonField = JsonMissing.of(), + @JsonProperty("view_type") + @ExcludeMissing + viewType: JsonField = JsonMissing.of(), + ) : this(objectId, objectType, name, options, userId, viewData, viewType, mutableMapOf()) /** - * Sets [Builder.objectId] to an arbitrary JSON value. + * The id of the object the view applies to * - * You should usually call [Builder.objectId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws BraintrustInvalidDataException 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 objectId(objectId: JsonField) = apply { body.objectId(objectId) } - - /** The object type that the ACL applies to */ - fun objectType(objectType: AclObjectType) = apply { body.objectType(objectType) } + fun objectId(): String = objectId.getRequired("object_id") /** - * Sets [Builder.objectType] to an arbitrary JSON value. + * The object type that the ACL applies to * - * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * @throws BraintrustInvalidDataException 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 objectType(objectType: JsonField) = apply { body.objectType(objectType) } - - /** Name of the view */ - fun name(name: String?) = apply { body.name(name) } - - /** Alias for calling [Builder.name] with `name.orElse(null)`. */ - fun name(name: Optional) = name(name.getOrNull()) + fun objectType(): AclObjectType = objectType.getRequired("object_type") /** - * Sets [Builder.name] to an arbitrary JSON value. + * Name of the view * - * 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. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun name(name: JsonField) = apply { body.name(name) } - - /** Options for the view in the app */ - fun options(options: ViewOptions?) = apply { body.options(options) } + fun name(): Optional = name.getOptional("name") - /** Alias for calling [Builder.options] with `options.orElse(null)`. */ - fun options(options: Optional) = options(options.getOrNull()) + /** + * Options for the view in the app + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun options(): Optional = options.getOptional("options") /** - * Sets [Builder.options] to an arbitrary JSON value. + * Identifies the user who created the view * - * You should usually call [Builder.options] with a well-typed [ViewOptions] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun options(options: JsonField) = apply { body.options(options) } + fun userId(): Optional = userId.getOptional("user_id") - /** Identifies the user who created the view */ - fun userId(userId: String?) = apply { body.userId(userId) } + /** + * The view definition + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun viewData(): Optional = viewData.getOptional("view_data") - /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ - fun userId(userId: Optional) = userId(userId.getOrNull()) + /** + * Type of table that the view corresponds to. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun viewType(): Optional = viewType.getOptional("view_type") /** - * Sets [Builder.userId] to an arbitrary JSON value. + * Returns the raw JSON value of [objectId]. * - * 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. + * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. */ - fun userId(userId: JsonField) = apply { body.userId(userId) } + @JsonProperty("object_id") @ExcludeMissing fun _objectId(): JsonField = objectId - /** The view definition */ - fun viewData(viewData: ViewData?) = apply { body.viewData(viewData) } + /** + * Returns the raw JSON value of [objectType]. + * + * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("object_type") + @ExcludeMissing + fun _objectType(): JsonField = objectType - /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ - fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) + /** + * 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 /** - * Sets [Builder.viewData] to an arbitrary JSON value. + * Returns the raw JSON value of [options]. * - * You should usually call [Builder.viewData] with a well-typed [ViewData] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. */ - fun viewData(viewData: JsonField) = apply { body.viewData(viewData) } + @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = options - /** Type of table that the view corresponds to. */ - fun viewType(viewType: ViewType?) = apply { body.viewType(viewType) } + /** + * 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 - /** Alias for calling [Builder.viewType] with `viewType.orElse(null)`. */ - fun viewType(viewType: Optional) = viewType(viewType.getOrNull()) + /** + * Returns the raw JSON value of [viewData]. + * + * Unlike [viewData], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("view_data") @ExcludeMissing fun _viewData(): JsonField = viewData /** - * Sets [Builder.viewType] to an arbitrary JSON value. + * Returns the raw JSON value of [viewType]. * - * You should usually call [Builder.viewType] with a well-typed [ViewType] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * Unlike [viewType], this method doesn't throw if the JSON field has an unexpected type. */ - fun viewType(viewType: JsonField) = apply { body.viewType(viewType) } + @JsonProperty("view_type") @ExcludeMissing fun _viewType(): JsonField = viewType - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) + @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 + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var objectId: JsonField? = null + private var objectType: JsonField? = null + private var name: JsonField = JsonMissing.of() + private var options: JsonField = JsonMissing.of() + private var userId: JsonField = JsonMissing.of() + private var viewData: JsonField = JsonMissing.of() + private var viewType: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + objectId = body.objectId + objectType = body.objectType + name = body.name + options = body.options + userId = body.userId + viewData = body.viewData + viewType = body.viewType + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** The id of the object the view applies to */ + fun objectId(objectId: String) = objectId(JsonField.of(objectId)) + + /** + * Sets [Builder.objectId] to an arbitrary JSON value. + * + * You should usually call [Builder.objectId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectId(objectId: JsonField) = apply { this.objectId = objectId } + + /** The object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = objectType(JsonField.of(objectType)) - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) + /** + * Sets [Builder.objectType] to an arbitrary JSON value. + * + * You should usually call [Builder.objectType] with a well-typed [AclObjectType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectType(objectType: JsonField) = apply { + this.objectType = objectType } - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** Name of the view */ + fun name(name: String?) = name(JsonField.ofNullable(name)) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * 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 additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** Options for the view in the app */ + fun options(options: ViewOptions?) = options(JsonField.ofNullable(options)) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** Alias for calling [Builder.options] with `options.orElse(null)`. */ + fun options(options: Optional) = options(options.getOrNull()) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * Sets [Builder.options] to an arbitrary JSON value. + * + * You should usually call [Builder.options] with a well-typed [ViewOptions] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun options(options: JsonField) = apply { this.options = options } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Identifies the user who created the view */ + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * 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 replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** The view definition */ + fun viewData(viewData: ViewData?) = viewData(JsonField.ofNullable(viewData)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ + fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.viewData] to an arbitrary JSON value. + * + * You should usually call [Builder.viewData] with a well-typed [ViewData] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun viewData(viewData: JsonField) = apply { this.viewData = viewData } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + /** Type of table that the view corresponds to. */ + fun viewType(viewType: ViewType?) = viewType(JsonField.ofNullable(viewType)) - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + /** Alias for calling [Builder.viewType] with `viewType.orElse(null)`. */ + fun viewType(viewType: Optional) = viewType(viewType.getOrNull()) - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** + * Sets [Builder.viewType] to an arbitrary JSON value. + * + * You should usually call [Builder.viewType] with a well-typed [ViewType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun viewType(viewType: JsonField) = apply { this.viewType = viewType } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } - - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + name, + options, + userId, + viewData, + viewType, + additionalProperties.toMutableMap(), + ) } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + private var validated: Boolean = false - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + fun validate(): Body = apply { + if (validated) { + return@apply } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + objectId() + objectType().validate() + name() + options().ifPresent { it.validate() } + userId() + viewData().ifPresent { it.validate() } + viewType().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + /** - * Returns an immutable instance of [ViewUpdateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * The following fields are required: - * ```java - * .viewId() - * .objectId() - * .objectType() - * ``` - * - * @throws IllegalStateException if any required field is unset. + * Used for best match union deserialization. */ - fun build(): ViewUpdateParams = - ViewUpdateParams( - checkRequired("viewId", viewId), - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + @JvmSynthetic + internal fun validity(): Int = + (if (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (options.asKnown().getOrNull()?.validity() ?: 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + (viewData.asKnown().getOrNull()?.validity() ?: 0) + + (viewType.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && objectId == other.objectId && objectType == other.objectType && name == other.name && options == other.options && userId == other.userId && viewData == other.viewData && viewType == other.viewType && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(objectId, objectType, name, options, userId, viewData, viewType, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{objectId=$objectId, objectType=$objectType, name=$name, options=$options, userId=$userId, viewData=$viewData, viewType=$viewType, additionalProperties=$additionalProperties}" } /** Type of table that the view corresponds to. */ @@ -939,6 +983,33 @@ private constructor( BraintrustInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ViewType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AclServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AclServiceAsyncImpl.kt index ab68729d..2cde27c7 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AclServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AclServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,7 +15,6 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Acl import com.braintrustdata.api.models.AclBatchUpdateParams import com.braintrustdata.api.models.AclBatchUpdateResponse @@ -22,6 +22,7 @@ import com.braintrustdata.api.models.AclCreateParams import com.braintrustdata.api.models.AclDeleteParams import com.braintrustdata.api.models.AclFindAndDeleteParams import com.braintrustdata.api.models.AclListPageAsync +import com.braintrustdata.api.models.AclListPageResponse import com.braintrustdata.api.models.AclListParams import com.braintrustdata.api.models.AclRetrieveParams import java.util.concurrent.CompletableFuture @@ -80,7 +81,7 @@ class AclServiceAsyncImpl internal constructor(private val clientOptions: Client class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : AclServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -122,7 +123,7 @@ class AclServiceAsyncImpl internal constructor(private val clientOptions: Client val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "acl", params.getPathParam(0)) + .addPathSegments("v1", "acl", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -141,8 +142,8 @@ class AclServiceAsyncImpl internal constructor(private val clientOptions: Client } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -168,7 +169,11 @@ class AclServiceAsyncImpl internal constructor(private val clientOptions: Client } } .let { - AclListPageAsync.of(AclServiceAsyncImpl(clientOptions), params, it) + AclListPageAsync.builder() + .service(AclServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -184,7 +189,7 @@ class AclServiceAsyncImpl internal constructor(private val clientOptions: Client val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "acl", params.getPathParam(0)) + .addPathSegments("v1", "acl", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepareAsync(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AiSecretServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AiSecretServiceAsyncImpl.kt index fbe03e82..5cd2d51e 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AiSecretServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AiSecretServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,12 +15,12 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.AISecret import com.braintrustdata.api.models.AiSecretCreateParams import com.braintrustdata.api.models.AiSecretDeleteParams import com.braintrustdata.api.models.AiSecretFindAndDeleteParams import com.braintrustdata.api.models.AiSecretListPageAsync +import com.braintrustdata.api.models.AiSecretListPageResponse import com.braintrustdata.api.models.AiSecretListParams import com.braintrustdata.api.models.AiSecretReplaceParams import com.braintrustdata.api.models.AiSecretRetrieveParams @@ -87,7 +88,7 @@ class AiSecretServiceAsyncImpl internal constructor(private val clientOptions: C class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : AiSecretServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -129,7 +130,7 @@ class AiSecretServiceAsyncImpl internal constructor(private val clientOptions: C val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "ai_secret", params.getPathParam(0)) + .addPathSegments("v1", "ai_secret", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -158,7 +159,7 @@ class AiSecretServiceAsyncImpl internal constructor(private val clientOptions: C val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "ai_secret", params.getPathParam(0)) + .addPathSegments("v1", "ai_secret", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -178,8 +179,8 @@ class AiSecretServiceAsyncImpl internal constructor(private val clientOptions: C } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -205,11 +206,11 @@ class AiSecretServiceAsyncImpl internal constructor(private val clientOptions: C } } .let { - AiSecretListPageAsync.of( - AiSecretServiceAsyncImpl(clientOptions), - params, - it, - ) + AiSecretListPageAsync.builder() + .service(AiSecretServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -225,7 +226,7 @@ class AiSecretServiceAsyncImpl internal constructor(private val clientOptions: C val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "ai_secret", params.getPathParam(0)) + .addPathSegments("v1", "ai_secret", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepareAsync(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ApiKeyServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ApiKeyServiceAsyncImpl.kt index ca00a3e4..c0298579 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ApiKeyServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ApiKeyServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.ApiKey import com.braintrustdata.api.models.ApiKeyCreateParams import com.braintrustdata.api.models.ApiKeyDeleteParams import com.braintrustdata.api.models.ApiKeyListPageAsync +import com.braintrustdata.api.models.ApiKeyListPageResponse import com.braintrustdata.api.models.ApiKeyListParams import com.braintrustdata.api.models.ApiKeyRetrieveParams import com.braintrustdata.api.models.CreateApiKeyOutput @@ -64,7 +65,7 @@ class ApiKeyServiceAsyncImpl internal constructor(private val clientOptions: Cli class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : ApiKeyServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -106,7 +107,7 @@ class ApiKeyServiceAsyncImpl internal constructor(private val clientOptions: Cli val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "api_key", params.getPathParam(0)) + .addPathSegments("v1", "api_key", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -125,8 +126,8 @@ class ApiKeyServiceAsyncImpl internal constructor(private val clientOptions: Cli } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -152,11 +153,11 @@ class ApiKeyServiceAsyncImpl internal constructor(private val clientOptions: Cli } } .let { - ApiKeyListPageAsync.of( - ApiKeyServiceAsyncImpl(clientOptions), - params, - it, - ) + ApiKeyListPageAsync.builder() + .service(ApiKeyServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -172,7 +173,7 @@ class ApiKeyServiceAsyncImpl internal constructor(private val clientOptions: Cli val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "api_key", params.getPathParam(0)) + .addPathSegments("v1", "api_key", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepareAsync(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/DatasetServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/DatasetServiceAsyncImpl.kt index 7a5002f9..14e26354 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/DatasetServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/DatasetServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,7 +15,6 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Dataset import com.braintrustdata.api.models.DatasetCreateParams import com.braintrustdata.api.models.DatasetDeleteParams @@ -23,6 +23,7 @@ import com.braintrustdata.api.models.DatasetFetchParams import com.braintrustdata.api.models.DatasetFetchPostParams import com.braintrustdata.api.models.DatasetInsertParams import com.braintrustdata.api.models.DatasetListPageAsync +import com.braintrustdata.api.models.DatasetListPageResponse import com.braintrustdata.api.models.DatasetListParams import com.braintrustdata.api.models.DatasetRetrieveParams import com.braintrustdata.api.models.DatasetSummarizeParams @@ -115,7 +116,7 @@ class DatasetServiceAsyncImpl internal constructor(private val clientOptions: Cl class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : DatasetServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -157,7 +158,7 @@ class DatasetServiceAsyncImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "dataset", params.getPathParam(0)) + .addPathSegments("v1", "dataset", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -186,7 +187,7 @@ class DatasetServiceAsyncImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "dataset", params.getPathParam(0)) + .addPathSegments("v1", "dataset", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -206,8 +207,8 @@ class DatasetServiceAsyncImpl internal constructor(private val clientOptions: Cl } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -233,11 +234,11 @@ class DatasetServiceAsyncImpl internal constructor(private val clientOptions: Cl } } .let { - DatasetListPageAsync.of( - DatasetServiceAsyncImpl(clientOptions), - params, - it, - ) + DatasetListPageAsync.builder() + .service(DatasetServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -253,7 +254,7 @@ class DatasetServiceAsyncImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "dataset", params.getPathParam(0)) + .addPathSegments("v1", "dataset", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepareAsync(clientOptions, params) @@ -284,7 +285,7 @@ class DatasetServiceAsyncImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "dataset", params.getPathParam(0), "feedback") + .addPathSegments("v1", "dataset", params._pathParam(0), "feedback") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -315,7 +316,7 @@ class DatasetServiceAsyncImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "dataset", params.getPathParam(0), "fetch") + .addPathSegments("v1", "dataset", params._pathParam(0), "fetch") .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -345,7 +346,7 @@ class DatasetServiceAsyncImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "dataset", params.getPathParam(0), "fetch") + .addPathSegments("v1", "dataset", params._pathParam(0), "fetch") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -376,7 +377,7 @@ class DatasetServiceAsyncImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "dataset", params.getPathParam(0), "insert") + .addPathSegments("v1", "dataset", params._pathParam(0), "insert") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -407,7 +408,7 @@ class DatasetServiceAsyncImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "dataset", params.getPathParam(0), "summarize") + .addPathSegments("v1", "dataset", params._pathParam(0), "summarize") .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EnvVarServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EnvVarServiceAsyncImpl.kt index c4ed7f35..a3480f74 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EnvVarServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EnvVarServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,7 +15,6 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.EnvVar import com.braintrustdata.api.models.EnvVarCreateParams import com.braintrustdata.api.models.EnvVarDeleteParams @@ -79,7 +79,7 @@ class EnvVarServiceAsyncImpl internal constructor(private val clientOptions: Cli class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : EnvVarServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -121,7 +121,7 @@ class EnvVarServiceAsyncImpl internal constructor(private val clientOptions: Cli val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "env_var", params.getPathParam(0)) + .addPathSegments("v1", "env_var", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -150,7 +150,7 @@ class EnvVarServiceAsyncImpl internal constructor(private val clientOptions: Cli val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "env_var", params.getPathParam(0)) + .addPathSegments("v1", "env_var", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -209,7 +209,7 @@ class EnvVarServiceAsyncImpl internal constructor(private val clientOptions: Cli val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "env_var", params.getPathParam(0)) + .addPathSegments("v1", "env_var", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepareAsync(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EvalServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EvalServiceAsyncImpl.kt index d0fc0019..619ae690 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EvalServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EvalServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,7 +15,6 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.EvalCreateParams import com.braintrustdata.api.models.SummarizeExperimentResponse import java.util.concurrent.CompletableFuture @@ -38,7 +38,7 @@ class EvalServiceAsyncImpl internal constructor(private val clientOptions: Clien class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : EvalServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ExperimentServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ExperimentServiceAsyncImpl.kt index 432baacd..1b41174a 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ExperimentServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ExperimentServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,7 +15,6 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Experiment import com.braintrustdata.api.models.ExperimentCreateParams import com.braintrustdata.api.models.ExperimentDeleteParams @@ -23,6 +23,7 @@ import com.braintrustdata.api.models.ExperimentFetchParams import com.braintrustdata.api.models.ExperimentFetchPostParams import com.braintrustdata.api.models.ExperimentInsertParams import com.braintrustdata.api.models.ExperimentListPageAsync +import com.braintrustdata.api.models.ExperimentListPageResponse import com.braintrustdata.api.models.ExperimentListParams import com.braintrustdata.api.models.ExperimentRetrieveParams import com.braintrustdata.api.models.ExperimentSummarizeParams @@ -115,7 +116,7 @@ class ExperimentServiceAsyncImpl internal constructor(private val clientOptions: class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : ExperimentServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -157,7 +158,7 @@ class ExperimentServiceAsyncImpl internal constructor(private val clientOptions: val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "experiment", params.getPathParam(0)) + .addPathSegments("v1", "experiment", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -186,7 +187,7 @@ class ExperimentServiceAsyncImpl internal constructor(private val clientOptions: val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "experiment", params.getPathParam(0)) + .addPathSegments("v1", "experiment", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -206,8 +207,8 @@ class ExperimentServiceAsyncImpl internal constructor(private val clientOptions: } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -233,11 +234,11 @@ class ExperimentServiceAsyncImpl internal constructor(private val clientOptions: } } .let { - ExperimentListPageAsync.of( - ExperimentServiceAsyncImpl(clientOptions), - params, - it, - ) + ExperimentListPageAsync.builder() + .service(ExperimentServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -253,7 +254,7 @@ class ExperimentServiceAsyncImpl internal constructor(private val clientOptions: val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "experiment", params.getPathParam(0)) + .addPathSegments("v1", "experiment", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepareAsync(clientOptions, params) @@ -284,7 +285,7 @@ class ExperimentServiceAsyncImpl internal constructor(private val clientOptions: val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "experiment", params.getPathParam(0), "feedback") + .addPathSegments("v1", "experiment", params._pathParam(0), "feedback") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -315,7 +316,7 @@ class ExperimentServiceAsyncImpl internal constructor(private val clientOptions: val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "experiment", params.getPathParam(0), "fetch") + .addPathSegments("v1", "experiment", params._pathParam(0), "fetch") .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -345,7 +346,7 @@ class ExperimentServiceAsyncImpl internal constructor(private val clientOptions: val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "experiment", params.getPathParam(0), "fetch") + .addPathSegments("v1", "experiment", params._pathParam(0), "fetch") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -376,7 +377,7 @@ class ExperimentServiceAsyncImpl internal constructor(private val clientOptions: val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "experiment", params.getPathParam(0), "insert") + .addPathSegments("v1", "experiment", params._pathParam(0), "insert") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -407,7 +408,7 @@ class ExperimentServiceAsyncImpl internal constructor(private val clientOptions: val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "experiment", params.getPathParam(0), "summarize") + .addPathSegments("v1", "experiment", params._pathParam(0), "summarize") .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/FunctionServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/FunctionServiceAsyncImpl.kt index 27377950..b646d9eb 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/FunctionServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/FunctionServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,13 +15,13 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Function import com.braintrustdata.api.models.FunctionCreateParams import com.braintrustdata.api.models.FunctionDeleteParams import com.braintrustdata.api.models.FunctionInvokeParams import com.braintrustdata.api.models.FunctionInvokeResponse import com.braintrustdata.api.models.FunctionListPageAsync +import com.braintrustdata.api.models.FunctionListPageResponse import com.braintrustdata.api.models.FunctionListParams import com.braintrustdata.api.models.FunctionReplaceParams import com.braintrustdata.api.models.FunctionRetrieveParams @@ -89,7 +90,7 @@ class FunctionServiceAsyncImpl internal constructor(private val clientOptions: C class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : FunctionServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -131,7 +132,7 @@ class FunctionServiceAsyncImpl internal constructor(private val clientOptions: C val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "function", params.getPathParam(0)) + .addPathSegments("v1", "function", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -160,7 +161,7 @@ class FunctionServiceAsyncImpl internal constructor(private val clientOptions: C val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "function", params.getPathParam(0)) + .addPathSegments("v1", "function", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -180,8 +181,8 @@ class FunctionServiceAsyncImpl internal constructor(private val clientOptions: C } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -207,11 +208,11 @@ class FunctionServiceAsyncImpl internal constructor(private val clientOptions: C } } .let { - FunctionListPageAsync.of( - FunctionServiceAsyncImpl(clientOptions), - params, - it, - ) + FunctionListPageAsync.builder() + .service(FunctionServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -227,7 +228,7 @@ class FunctionServiceAsyncImpl internal constructor(private val clientOptions: C val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "function", params.getPathParam(0)) + .addPathSegments("v1", "function", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepareAsync(clientOptions, params) @@ -258,7 +259,7 @@ class FunctionServiceAsyncImpl internal constructor(private val clientOptions: C val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "function", params.getPathParam(0), "invoke") + .addPathSegments("v1", "function", params._pathParam(0), "invoke") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/GroupServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/GroupServiceAsyncImpl.kt index db541802..e434a12f 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/GroupServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/GroupServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Group import com.braintrustdata.api.models.GroupCreateParams import com.braintrustdata.api.models.GroupDeleteParams import com.braintrustdata.api.models.GroupListPageAsync +import com.braintrustdata.api.models.GroupListPageResponse import com.braintrustdata.api.models.GroupListParams import com.braintrustdata.api.models.GroupReplaceParams import com.braintrustdata.api.models.GroupRetrieveParams @@ -79,7 +80,7 @@ class GroupServiceAsyncImpl internal constructor(private val clientOptions: Clie class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : GroupServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -121,7 +122,7 @@ class GroupServiceAsyncImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "group", params.getPathParam(0)) + .addPathSegments("v1", "group", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -150,7 +151,7 @@ class GroupServiceAsyncImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "group", params.getPathParam(0)) + .addPathSegments("v1", "group", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -170,8 +171,8 @@ class GroupServiceAsyncImpl internal constructor(private val clientOptions: Clie } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -197,11 +198,11 @@ class GroupServiceAsyncImpl internal constructor(private val clientOptions: Clie } } .let { - GroupListPageAsync.of( - GroupServiceAsyncImpl(clientOptions), - params, - it, - ) + GroupListPageAsync.builder() + .service(GroupServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -217,7 +218,7 @@ class GroupServiceAsyncImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "group", params.getPathParam(0)) + .addPathSegments("v1", "group", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepareAsync(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/OrganizationServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/OrganizationServiceAsyncImpl.kt index 08667293..00950daa 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/OrganizationServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/OrganizationServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,10 +15,10 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Organization import com.braintrustdata.api.models.OrganizationDeleteParams import com.braintrustdata.api.models.OrganizationListPageAsync +import com.braintrustdata.api.models.OrganizationListPageResponse import com.braintrustdata.api.models.OrganizationListParams import com.braintrustdata.api.models.OrganizationRetrieveParams import com.braintrustdata.api.models.OrganizationUpdateParams @@ -69,7 +70,7 @@ class OrganizationServiceAsyncImpl internal constructor(private val clientOption class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : OrganizationServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val members: MemberServiceAsync.WithRawResponse by lazy { MemberServiceAsyncImpl.WithRawResponseImpl(clientOptions) @@ -87,7 +88,7 @@ class OrganizationServiceAsyncImpl internal constructor(private val clientOption val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "organization", params.getPathParam(0)) + .addPathSegments("v1", "organization", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -116,7 +117,7 @@ class OrganizationServiceAsyncImpl internal constructor(private val clientOption val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "organization", params.getPathParam(0)) + .addPathSegments("v1", "organization", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -136,8 +137,8 @@ class OrganizationServiceAsyncImpl internal constructor(private val clientOption } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -163,11 +164,11 @@ class OrganizationServiceAsyncImpl internal constructor(private val clientOption } } .let { - OrganizationListPageAsync.of( - OrganizationServiceAsyncImpl(clientOptions), - params, - it, - ) + OrganizationListPageAsync.builder() + .service(OrganizationServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -183,7 +184,7 @@ class OrganizationServiceAsyncImpl internal constructor(private val clientOption val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "organization", params.getPathParam(0)) + .addPathSegments("v1", "organization", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepareAsync(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectScoreServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectScoreServiceAsyncImpl.kt index cde96d23..3d22e48b 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectScoreServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectScoreServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.ProjectScore import com.braintrustdata.api.models.ProjectScoreCreateParams import com.braintrustdata.api.models.ProjectScoreDeleteParams import com.braintrustdata.api.models.ProjectScoreListPageAsync +import com.braintrustdata.api.models.ProjectScoreListPageResponse import com.braintrustdata.api.models.ProjectScoreListParams import com.braintrustdata.api.models.ProjectScoreReplaceParams import com.braintrustdata.api.models.ProjectScoreRetrieveParams @@ -79,7 +80,7 @@ class ProjectScoreServiceAsyncImpl internal constructor(private val clientOption class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : ProjectScoreServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -121,7 +122,7 @@ class ProjectScoreServiceAsyncImpl internal constructor(private val clientOption val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "project_score", params.getPathParam(0)) + .addPathSegments("v1", "project_score", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -150,7 +151,7 @@ class ProjectScoreServiceAsyncImpl internal constructor(private val clientOption val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "project_score", params.getPathParam(0)) + .addPathSegments("v1", "project_score", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -170,8 +171,8 @@ class ProjectScoreServiceAsyncImpl internal constructor(private val clientOption } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -197,11 +198,11 @@ class ProjectScoreServiceAsyncImpl internal constructor(private val clientOption } } .let { - ProjectScoreListPageAsync.of( - ProjectScoreServiceAsyncImpl(clientOptions), - params, - it, - ) + ProjectScoreListPageAsync.builder() + .service(ProjectScoreServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -217,7 +218,7 @@ class ProjectScoreServiceAsyncImpl internal constructor(private val clientOption val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "project_score", params.getPathParam(0)) + .addPathSegments("v1", "project_score", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepareAsync(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectServiceAsyncImpl.kt index dba161a5..0953c5f2 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Project import com.braintrustdata.api.models.ProjectCreateParams import com.braintrustdata.api.models.ProjectDeleteParams import com.braintrustdata.api.models.ProjectListPageAsync +import com.braintrustdata.api.models.ProjectListPageResponse import com.braintrustdata.api.models.ProjectListParams import com.braintrustdata.api.models.ProjectRetrieveParams import com.braintrustdata.api.models.ProjectUpdateParams @@ -77,7 +78,7 @@ class ProjectServiceAsyncImpl internal constructor(private val clientOptions: Cl class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : ProjectServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val logs: LogServiceAsync.WithRawResponse by lazy { LogServiceAsyncImpl.WithRawResponseImpl(clientOptions) @@ -125,7 +126,7 @@ class ProjectServiceAsyncImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "project", params.getPathParam(0)) + .addPathSegments("v1", "project", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -154,7 +155,7 @@ class ProjectServiceAsyncImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "project", params.getPathParam(0)) + .addPathSegments("v1", "project", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -174,8 +175,8 @@ class ProjectServiceAsyncImpl internal constructor(private val clientOptions: Cl } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -201,11 +202,11 @@ class ProjectServiceAsyncImpl internal constructor(private val clientOptions: Cl } } .let { - ProjectListPageAsync.of( - ProjectServiceAsyncImpl(clientOptions), - params, - it, - ) + ProjectListPageAsync.builder() + .service(ProjectServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -221,7 +222,7 @@ class ProjectServiceAsyncImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "project", params.getPathParam(0)) + .addPathSegments("v1", "project", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepareAsync(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectTagServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectTagServiceAsyncImpl.kt index d12a821a..193e671e 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectTagServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectTagServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.ProjectTag import com.braintrustdata.api.models.ProjectTagCreateParams import com.braintrustdata.api.models.ProjectTagDeleteParams import com.braintrustdata.api.models.ProjectTagListPageAsync +import com.braintrustdata.api.models.ProjectTagListPageResponse import com.braintrustdata.api.models.ProjectTagListParams import com.braintrustdata.api.models.ProjectTagReplaceParams import com.braintrustdata.api.models.ProjectTagRetrieveParams @@ -79,7 +80,7 @@ class ProjectTagServiceAsyncImpl internal constructor(private val clientOptions: class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : ProjectTagServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -121,7 +122,7 @@ class ProjectTagServiceAsyncImpl internal constructor(private val clientOptions: val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "project_tag", params.getPathParam(0)) + .addPathSegments("v1", "project_tag", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -150,7 +151,7 @@ class ProjectTagServiceAsyncImpl internal constructor(private val clientOptions: val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "project_tag", params.getPathParam(0)) + .addPathSegments("v1", "project_tag", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -170,8 +171,8 @@ class ProjectTagServiceAsyncImpl internal constructor(private val clientOptions: } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -197,11 +198,11 @@ class ProjectTagServiceAsyncImpl internal constructor(private val clientOptions: } } .let { - ProjectTagListPageAsync.of( - ProjectTagServiceAsyncImpl(clientOptions), - params, - it, - ) + ProjectTagListPageAsync.builder() + .service(ProjectTagServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -217,7 +218,7 @@ class ProjectTagServiceAsyncImpl internal constructor(private val clientOptions: val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "project_tag", params.getPathParam(0)) + .addPathSegments("v1", "project_tag", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepareAsync(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/PromptServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/PromptServiceAsyncImpl.kt index 7772aa68..32bdece7 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/PromptServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/PromptServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Prompt import com.braintrustdata.api.models.PromptCreateParams import com.braintrustdata.api.models.PromptDeleteParams import com.braintrustdata.api.models.PromptListPageAsync +import com.braintrustdata.api.models.PromptListPageResponse import com.braintrustdata.api.models.PromptListParams import com.braintrustdata.api.models.PromptReplaceParams import com.braintrustdata.api.models.PromptRetrieveParams @@ -79,7 +80,7 @@ class PromptServiceAsyncImpl internal constructor(private val clientOptions: Cli class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : PromptServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -121,7 +122,7 @@ class PromptServiceAsyncImpl internal constructor(private val clientOptions: Cli val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "prompt", params.getPathParam(0)) + .addPathSegments("v1", "prompt", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -150,7 +151,7 @@ class PromptServiceAsyncImpl internal constructor(private val clientOptions: Cli val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "prompt", params.getPathParam(0)) + .addPathSegments("v1", "prompt", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -170,8 +171,8 @@ class PromptServiceAsyncImpl internal constructor(private val clientOptions: Cli } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -197,11 +198,11 @@ class PromptServiceAsyncImpl internal constructor(private val clientOptions: Cli } } .let { - PromptListPageAsync.of( - PromptServiceAsyncImpl(clientOptions), - params, - it, - ) + PromptListPageAsync.builder() + .service(PromptServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -217,7 +218,7 @@ class PromptServiceAsyncImpl internal constructor(private val clientOptions: Cli val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "prompt", params.getPathParam(0)) + .addPathSegments("v1", "prompt", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepareAsync(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/RoleServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/RoleServiceAsyncImpl.kt index f4809686..0da885cc 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/RoleServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/RoleServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Role import com.braintrustdata.api.models.RoleCreateParams import com.braintrustdata.api.models.RoleDeleteParams import com.braintrustdata.api.models.RoleListPageAsync +import com.braintrustdata.api.models.RoleListPageResponse import com.braintrustdata.api.models.RoleListParams import com.braintrustdata.api.models.RoleReplaceParams import com.braintrustdata.api.models.RoleRetrieveParams @@ -79,7 +80,7 @@ class RoleServiceAsyncImpl internal constructor(private val clientOptions: Clien class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : RoleServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -121,7 +122,7 @@ class RoleServiceAsyncImpl internal constructor(private val clientOptions: Clien val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "role", params.getPathParam(0)) + .addPathSegments("v1", "role", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -150,7 +151,7 @@ class RoleServiceAsyncImpl internal constructor(private val clientOptions: Clien val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "role", params.getPathParam(0)) + .addPathSegments("v1", "role", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -170,8 +171,8 @@ class RoleServiceAsyncImpl internal constructor(private val clientOptions: Clien } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -197,11 +198,11 @@ class RoleServiceAsyncImpl internal constructor(private val clientOptions: Clien } } .let { - RoleListPageAsync.of( - RoleServiceAsyncImpl(clientOptions), - params, - it, - ) + RoleListPageAsync.builder() + .service(RoleServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -217,7 +218,7 @@ class RoleServiceAsyncImpl internal constructor(private val clientOptions: Clien val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "role", params.getPathParam(0)) + .addPathSegments("v1", "role", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepareAsync(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/SpanIframeServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/SpanIframeServiceAsyncImpl.kt index 6dd3a6b3..843f6b1e 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/SpanIframeServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/SpanIframeServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.SpanIFrame import com.braintrustdata.api.models.SpanIframeCreateParams import com.braintrustdata.api.models.SpanIframeDeleteParams import com.braintrustdata.api.models.SpanIframeListPageAsync +import com.braintrustdata.api.models.SpanIframeListPageResponse import com.braintrustdata.api.models.SpanIframeListParams import com.braintrustdata.api.models.SpanIframeReplaceParams import com.braintrustdata.api.models.SpanIframeRetrieveParams @@ -79,7 +80,7 @@ class SpanIframeServiceAsyncImpl internal constructor(private val clientOptions: class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : SpanIframeServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -121,7 +122,7 @@ class SpanIframeServiceAsyncImpl internal constructor(private val clientOptions: val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "span_iframe", params.getPathParam(0)) + .addPathSegments("v1", "span_iframe", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -150,7 +151,7 @@ class SpanIframeServiceAsyncImpl internal constructor(private val clientOptions: val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "span_iframe", params.getPathParam(0)) + .addPathSegments("v1", "span_iframe", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -170,8 +171,8 @@ class SpanIframeServiceAsyncImpl internal constructor(private val clientOptions: } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -197,11 +198,11 @@ class SpanIframeServiceAsyncImpl internal constructor(private val clientOptions: } } .let { - SpanIframeListPageAsync.of( - SpanIframeServiceAsyncImpl(clientOptions), - params, - it, - ) + SpanIframeListPageAsync.builder() + .service(SpanIframeServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -217,7 +218,7 @@ class SpanIframeServiceAsyncImpl internal constructor(private val clientOptions: val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "span_iframe", params.getPathParam(0)) + .addPathSegments("v1", "span_iframe", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepareAsync(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/TopLevelServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/TopLevelServiceAsyncImpl.kt index efc7d4ce..26749e99 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/TopLevelServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/TopLevelServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.stringHandler @@ -13,7 +14,6 @@ import com.braintrustdata.api.core.http.HttpResponse.Handler import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.TopLevelHelloWorldParams import java.util.concurrent.CompletableFuture @@ -36,7 +36,7 @@ class TopLevelServiceAsyncImpl internal constructor(private val clientOptions: C class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : TopLevelServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val helloWorldHandler: Handler = stringHandler().withErrorHandler(errorHandler) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/UserServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/UserServiceAsyncImpl.kt index 54c73c41..b5d79eb8 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/UserServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/UserServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -13,9 +14,9 @@ import com.braintrustdata.api.core.http.HttpResponse.Handler import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.User import com.braintrustdata.api.models.UserListPageAsync +import com.braintrustdata.api.models.UserListPageResponse import com.braintrustdata.api.models.UserListParams import com.braintrustdata.api.models.UserRetrieveParams import java.util.concurrent.CompletableFuture @@ -46,7 +47,7 @@ class UserServiceAsyncImpl internal constructor(private val clientOptions: Clien class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : UserServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -58,7 +59,7 @@ class UserServiceAsyncImpl internal constructor(private val clientOptions: Clien val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "user", params.getPathParam(0)) + .addPathSegments("v1", "user", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -77,8 +78,8 @@ class UserServiceAsyncImpl internal constructor(private val clientOptions: Clien } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -104,11 +105,11 @@ class UserServiceAsyncImpl internal constructor(private val clientOptions: Clien } } .let { - UserListPageAsync.of( - UserServiceAsyncImpl(clientOptions), - params, - it, - ) + UserListPageAsync.builder() + .service(UserServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ViewServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ViewServiceAsyncImpl.kt index 644bd149..35a95111 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ViewServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ViewServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.View import com.braintrustdata.api.models.ViewCreateParams import com.braintrustdata.api.models.ViewDeleteParams import com.braintrustdata.api.models.ViewListPageAsync +import com.braintrustdata.api.models.ViewListPageResponse import com.braintrustdata.api.models.ViewListParams import com.braintrustdata.api.models.ViewReplaceParams import com.braintrustdata.api.models.ViewRetrieveParams @@ -79,7 +80,7 @@ class ViewServiceAsyncImpl internal constructor(private val clientOptions: Clien class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : ViewServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -121,7 +122,7 @@ class ViewServiceAsyncImpl internal constructor(private val clientOptions: Clien val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "view", params.getPathParam(0)) + .addPathSegments("v1", "view", params._pathParam(0)) .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -150,7 +151,7 @@ class ViewServiceAsyncImpl internal constructor(private val clientOptions: Clien val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "view", params.getPathParam(0)) + .addPathSegments("v1", "view", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -170,8 +171,8 @@ class ViewServiceAsyncImpl internal constructor(private val clientOptions: Clien } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -197,11 +198,11 @@ class ViewServiceAsyncImpl internal constructor(private val clientOptions: Clien } } .let { - ViewListPageAsync.of( - ViewServiceAsyncImpl(clientOptions), - params, - it, - ) + ViewListPageAsync.builder() + .service(ViewServiceAsyncImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -217,7 +218,7 @@ class ViewServiceAsyncImpl internal constructor(private val clientOptions: Clien val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "view", params.getPathParam(0)) + .addPathSegments("v1", "view", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/organizations/MemberServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/organizations/MemberServiceAsyncImpl.kt index ac1cca4a..40d22d7b 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/organizations/MemberServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/organizations/MemberServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async.organizations import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,7 +15,6 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.OrganizationMemberUpdateParams import com.braintrustdata.api.models.PatchOrganizationMembersOutput import java.util.concurrent.CompletableFuture @@ -38,7 +38,7 @@ class MemberServiceAsyncImpl internal constructor(private val clientOptions: Cli class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : MemberServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/projects/LogServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/projects/LogServiceAsyncImpl.kt index 7c47266f..477e9056 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/projects/LogServiceAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/projects/LogServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.async.projects import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,7 +15,6 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepareAsync -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.FeedbackResponseSchema import com.braintrustdata.api.models.FetchProjectLogsEventsResponse import com.braintrustdata.api.models.InsertEventsResponse @@ -64,7 +64,7 @@ class LogServiceAsyncImpl internal constructor(private val clientOptions: Client class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : LogServiceAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val feedbackHandler: Handler = jsonHandler(clientOptions.jsonMapper) @@ -77,7 +77,7 @@ class LogServiceAsyncImpl internal constructor(private val clientOptions: Client val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "feedback") + .addPathSegments("v1", "project_logs", params._pathParam(0), "feedback") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -108,7 +108,7 @@ class LogServiceAsyncImpl internal constructor(private val clientOptions: Client val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "fetch") + .addPathSegments("v1", "project_logs", params._pathParam(0), "fetch") .build() .prepareAsync(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -138,7 +138,7 @@ class LogServiceAsyncImpl internal constructor(private val clientOptions: Client val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "fetch") + .addPathSegments("v1", "project_logs", params._pathParam(0), "fetch") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) @@ -169,7 +169,7 @@ class LogServiceAsyncImpl internal constructor(private val clientOptions: Client val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "insert") + .addPathSegments("v1", "project_logs", params._pathParam(0), "insert") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepareAsync(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AclServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AclServiceImpl.kt index b6a1b9e0..6511ad61 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AclServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AclServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,7 +15,6 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Acl import com.braintrustdata.api.models.AclBatchUpdateParams import com.braintrustdata.api.models.AclBatchUpdateResponse @@ -22,6 +22,7 @@ import com.braintrustdata.api.models.AclCreateParams import com.braintrustdata.api.models.AclDeleteParams import com.braintrustdata.api.models.AclFindAndDeleteParams import com.braintrustdata.api.models.AclListPage +import com.braintrustdata.api.models.AclListPageResponse import com.braintrustdata.api.models.AclListParams import com.braintrustdata.api.models.AclRetrieveParams @@ -66,7 +67,7 @@ class AclServiceImpl internal constructor(private val clientOptions: ClientOptio class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : AclService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -105,7 +106,7 @@ class AclServiceImpl internal constructor(private val clientOptions: ClientOptio val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "acl", params.getPathParam(0)) + .addPathSegments("v1", "acl", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -121,8 +122,8 @@ class AclServiceImpl internal constructor(private val clientOptions: ClientOptio } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -145,7 +146,13 @@ class AclServiceImpl internal constructor(private val clientOptions: ClientOptio it.validate() } } - .let { AclListPage.of(AclServiceImpl(clientOptions), params, it) } + .let { + AclListPage.builder() + .service(AclServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } } @@ -159,7 +166,7 @@ class AclServiceImpl internal constructor(private val clientOptions: ClientOptio val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "acl", params.getPathParam(0)) + .addPathSegments("v1", "acl", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepare(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AiSecretServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AiSecretServiceImpl.kt index 8824fdce..e5da7242 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AiSecretServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AiSecretServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,12 +15,12 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.AISecret import com.braintrustdata.api.models.AiSecretCreateParams import com.braintrustdata.api.models.AiSecretDeleteParams import com.braintrustdata.api.models.AiSecretFindAndDeleteParams import com.braintrustdata.api.models.AiSecretListPage +import com.braintrustdata.api.models.AiSecretListPageResponse import com.braintrustdata.api.models.AiSecretListParams import com.braintrustdata.api.models.AiSecretReplaceParams import com.braintrustdata.api.models.AiSecretRetrieveParams @@ -74,7 +75,7 @@ class AiSecretServiceImpl internal constructor(private val clientOptions: Client class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : AiSecretService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -113,7 +114,7 @@ class AiSecretServiceImpl internal constructor(private val clientOptions: Client val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "ai_secret", params.getPathParam(0)) + .addPathSegments("v1", "ai_secret", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -139,7 +140,7 @@ class AiSecretServiceImpl internal constructor(private val clientOptions: Client val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "ai_secret", params.getPathParam(0)) + .addPathSegments("v1", "ai_secret", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -156,8 +157,8 @@ class AiSecretServiceImpl internal constructor(private val clientOptions: Client } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -180,7 +181,13 @@ class AiSecretServiceImpl internal constructor(private val clientOptions: Client it.validate() } } - .let { AiSecretListPage.of(AiSecretServiceImpl(clientOptions), params, it) } + .let { + AiSecretListPage.builder() + .service(AiSecretServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } } @@ -194,7 +201,7 @@ class AiSecretServiceImpl internal constructor(private val clientOptions: Client val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "ai_secret", params.getPathParam(0)) + .addPathSegments("v1", "ai_secret", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepare(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ApiKeyServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ApiKeyServiceImpl.kt index cba100a5..dd948b0d 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ApiKeyServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ApiKeyServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.ApiKey import com.braintrustdata.api.models.ApiKeyCreateParams import com.braintrustdata.api.models.ApiKeyDeleteParams import com.braintrustdata.api.models.ApiKeyListPage +import com.braintrustdata.api.models.ApiKeyListPageResponse import com.braintrustdata.api.models.ApiKeyListParams import com.braintrustdata.api.models.ApiKeyRetrieveParams import com.braintrustdata.api.models.CreateApiKeyOutput @@ -54,7 +55,7 @@ class ApiKeyServiceImpl internal constructor(private val clientOptions: ClientOp class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : ApiKeyService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -93,7 +94,7 @@ class ApiKeyServiceImpl internal constructor(private val clientOptions: ClientOp val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "api_key", params.getPathParam(0)) + .addPathSegments("v1", "api_key", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -109,8 +110,8 @@ class ApiKeyServiceImpl internal constructor(private val clientOptions: ClientOp } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -133,7 +134,13 @@ class ApiKeyServiceImpl internal constructor(private val clientOptions: ClientOp it.validate() } } - .let { ApiKeyListPage.of(ApiKeyServiceImpl(clientOptions), params, it) } + .let { + ApiKeyListPage.builder() + .service(ApiKeyServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } } @@ -147,7 +154,7 @@ class ApiKeyServiceImpl internal constructor(private val clientOptions: ClientOp val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "api_key", params.getPathParam(0)) + .addPathSegments("v1", "api_key", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepare(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/DatasetServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/DatasetServiceImpl.kt index 033ed993..39a0a0e3 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/DatasetServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/DatasetServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,7 +15,6 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Dataset import com.braintrustdata.api.models.DatasetCreateParams import com.braintrustdata.api.models.DatasetDeleteParams @@ -23,6 +23,7 @@ import com.braintrustdata.api.models.DatasetFetchParams import com.braintrustdata.api.models.DatasetFetchPostParams import com.braintrustdata.api.models.DatasetInsertParams import com.braintrustdata.api.models.DatasetListPage +import com.braintrustdata.api.models.DatasetListPageResponse import com.braintrustdata.api.models.DatasetListParams import com.braintrustdata.api.models.DatasetRetrieveParams import com.braintrustdata.api.models.DatasetSummarizeParams @@ -99,7 +100,7 @@ class DatasetServiceImpl internal constructor(private val clientOptions: ClientO class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : DatasetService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -138,7 +139,7 @@ class DatasetServiceImpl internal constructor(private val clientOptions: ClientO val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "dataset", params.getPathParam(0)) + .addPathSegments("v1", "dataset", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -164,7 +165,7 @@ class DatasetServiceImpl internal constructor(private val clientOptions: ClientO val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "dataset", params.getPathParam(0)) + .addPathSegments("v1", "dataset", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -181,8 +182,8 @@ class DatasetServiceImpl internal constructor(private val clientOptions: ClientO } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -205,7 +206,13 @@ class DatasetServiceImpl internal constructor(private val clientOptions: ClientO it.validate() } } - .let { DatasetListPage.of(DatasetServiceImpl(clientOptions), params, it) } + .let { + DatasetListPage.builder() + .service(DatasetServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } } @@ -219,7 +226,7 @@ class DatasetServiceImpl internal constructor(private val clientOptions: ClientO val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "dataset", params.getPathParam(0)) + .addPathSegments("v1", "dataset", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepare(clientOptions, params) @@ -247,7 +254,7 @@ class DatasetServiceImpl internal constructor(private val clientOptions: ClientO val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "dataset", params.getPathParam(0), "feedback") + .addPathSegments("v1", "dataset", params._pathParam(0), "feedback") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -275,7 +282,7 @@ class DatasetServiceImpl internal constructor(private val clientOptions: ClientO val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "dataset", params.getPathParam(0), "fetch") + .addPathSegments("v1", "dataset", params._pathParam(0), "fetch") .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -302,7 +309,7 @@ class DatasetServiceImpl internal constructor(private val clientOptions: ClientO val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "dataset", params.getPathParam(0), "fetch") + .addPathSegments("v1", "dataset", params._pathParam(0), "fetch") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -330,7 +337,7 @@ class DatasetServiceImpl internal constructor(private val clientOptions: ClientO val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "dataset", params.getPathParam(0), "insert") + .addPathSegments("v1", "dataset", params._pathParam(0), "insert") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -358,7 +365,7 @@ class DatasetServiceImpl internal constructor(private val clientOptions: ClientO val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "dataset", params.getPathParam(0), "summarize") + .addPathSegments("v1", "dataset", params._pathParam(0), "summarize") .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EnvVarServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EnvVarServiceImpl.kt index aa611b8f..042d24b9 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EnvVarServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EnvVarServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,7 +15,6 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.EnvVar import com.braintrustdata.api.models.EnvVarCreateParams import com.braintrustdata.api.models.EnvVarDeleteParams @@ -63,7 +63,7 @@ class EnvVarServiceImpl internal constructor(private val clientOptions: ClientOp class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : EnvVarService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -102,7 +102,7 @@ class EnvVarServiceImpl internal constructor(private val clientOptions: ClientOp val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "env_var", params.getPathParam(0)) + .addPathSegments("v1", "env_var", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -128,7 +128,7 @@ class EnvVarServiceImpl internal constructor(private val clientOptions: ClientOp val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "env_var", params.getPathParam(0)) + .addPathSegments("v1", "env_var", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -181,7 +181,7 @@ class EnvVarServiceImpl internal constructor(private val clientOptions: ClientOp val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "env_var", params.getPathParam(0)) + .addPathSegments("v1", "env_var", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepare(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EvalServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EvalServiceImpl.kt index e761eba5..c590863e 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EvalServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EvalServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,7 +15,6 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.EvalCreateParams import com.braintrustdata.api.models.SummarizeExperimentResponse @@ -36,7 +36,7 @@ class EvalServiceImpl internal constructor(private val clientOptions: ClientOpti class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : EvalService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ExperimentServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ExperimentServiceImpl.kt index 7ec0526e..f7d1da12 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ExperimentServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ExperimentServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,7 +15,6 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Experiment import com.braintrustdata.api.models.ExperimentCreateParams import com.braintrustdata.api.models.ExperimentDeleteParams @@ -23,6 +23,7 @@ import com.braintrustdata.api.models.ExperimentFetchParams import com.braintrustdata.api.models.ExperimentFetchPostParams import com.braintrustdata.api.models.ExperimentInsertParams import com.braintrustdata.api.models.ExperimentListPage +import com.braintrustdata.api.models.ExperimentListPageResponse import com.braintrustdata.api.models.ExperimentListParams import com.braintrustdata.api.models.ExperimentRetrieveParams import com.braintrustdata.api.models.ExperimentSummarizeParams @@ -114,7 +115,7 @@ class ExperimentServiceImpl internal constructor(private val clientOptions: Clie class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : ExperimentService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -153,7 +154,7 @@ class ExperimentServiceImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "experiment", params.getPathParam(0)) + .addPathSegments("v1", "experiment", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -179,7 +180,7 @@ class ExperimentServiceImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "experiment", params.getPathParam(0)) + .addPathSegments("v1", "experiment", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -196,8 +197,8 @@ class ExperimentServiceImpl internal constructor(private val clientOptions: Clie } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -220,7 +221,13 @@ class ExperimentServiceImpl internal constructor(private val clientOptions: Clie it.validate() } } - .let { ExperimentListPage.of(ExperimentServiceImpl(clientOptions), params, it) } + .let { + ExperimentListPage.builder() + .service(ExperimentServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } } @@ -234,7 +241,7 @@ class ExperimentServiceImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "experiment", params.getPathParam(0)) + .addPathSegments("v1", "experiment", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepare(clientOptions, params) @@ -262,7 +269,7 @@ class ExperimentServiceImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "experiment", params.getPathParam(0), "feedback") + .addPathSegments("v1", "experiment", params._pathParam(0), "feedback") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -290,7 +297,7 @@ class ExperimentServiceImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "experiment", params.getPathParam(0), "fetch") + .addPathSegments("v1", "experiment", params._pathParam(0), "fetch") .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -317,7 +324,7 @@ class ExperimentServiceImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "experiment", params.getPathParam(0), "fetch") + .addPathSegments("v1", "experiment", params._pathParam(0), "fetch") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -345,7 +352,7 @@ class ExperimentServiceImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "experiment", params.getPathParam(0), "insert") + .addPathSegments("v1", "experiment", params._pathParam(0), "insert") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -373,7 +380,7 @@ class ExperimentServiceImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "experiment", params.getPathParam(0), "summarize") + .addPathSegments("v1", "experiment", params._pathParam(0), "summarize") .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/FunctionServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/FunctionServiceImpl.kt index cf7eb4ad..9658b5bc 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/FunctionServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/FunctionServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,13 +15,13 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Function import com.braintrustdata.api.models.FunctionCreateParams import com.braintrustdata.api.models.FunctionDeleteParams import com.braintrustdata.api.models.FunctionInvokeParams import com.braintrustdata.api.models.FunctionInvokeResponse import com.braintrustdata.api.models.FunctionListPage +import com.braintrustdata.api.models.FunctionListPageResponse import com.braintrustdata.api.models.FunctionListParams import com.braintrustdata.api.models.FunctionReplaceParams import com.braintrustdata.api.models.FunctionRetrieveParams @@ -76,7 +77,7 @@ class FunctionServiceImpl internal constructor(private val clientOptions: Client class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : FunctionService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -115,7 +116,7 @@ class FunctionServiceImpl internal constructor(private val clientOptions: Client val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "function", params.getPathParam(0)) + .addPathSegments("v1", "function", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -141,7 +142,7 @@ class FunctionServiceImpl internal constructor(private val clientOptions: Client val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "function", params.getPathParam(0)) + .addPathSegments("v1", "function", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -158,8 +159,8 @@ class FunctionServiceImpl internal constructor(private val clientOptions: Client } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -182,7 +183,13 @@ class FunctionServiceImpl internal constructor(private val clientOptions: Client it.validate() } } - .let { FunctionListPage.of(FunctionServiceImpl(clientOptions), params, it) } + .let { + FunctionListPage.builder() + .service(FunctionServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } } @@ -196,7 +203,7 @@ class FunctionServiceImpl internal constructor(private val clientOptions: Client val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "function", params.getPathParam(0)) + .addPathSegments("v1", "function", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepare(clientOptions, params) @@ -224,7 +231,7 @@ class FunctionServiceImpl internal constructor(private val clientOptions: Client val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "function", params.getPathParam(0), "invoke") + .addPathSegments("v1", "function", params._pathParam(0), "invoke") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/GroupServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/GroupServiceImpl.kt index 84a146af..30e51563 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/GroupServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/GroupServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Group import com.braintrustdata.api.models.GroupCreateParams import com.braintrustdata.api.models.GroupDeleteParams import com.braintrustdata.api.models.GroupListPage +import com.braintrustdata.api.models.GroupListPageResponse import com.braintrustdata.api.models.GroupListParams import com.braintrustdata.api.models.GroupReplaceParams import com.braintrustdata.api.models.GroupRetrieveParams @@ -60,7 +61,7 @@ class GroupServiceImpl internal constructor(private val clientOptions: ClientOpt class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : GroupService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -99,7 +100,7 @@ class GroupServiceImpl internal constructor(private val clientOptions: ClientOpt val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "group", params.getPathParam(0)) + .addPathSegments("v1", "group", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -125,7 +126,7 @@ class GroupServiceImpl internal constructor(private val clientOptions: ClientOpt val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "group", params.getPathParam(0)) + .addPathSegments("v1", "group", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -142,8 +143,8 @@ class GroupServiceImpl internal constructor(private val clientOptions: ClientOpt } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -166,7 +167,13 @@ class GroupServiceImpl internal constructor(private val clientOptions: ClientOpt it.validate() } } - .let { GroupListPage.of(GroupServiceImpl(clientOptions), params, it) } + .let { + GroupListPage.builder() + .service(GroupServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } } @@ -180,7 +187,7 @@ class GroupServiceImpl internal constructor(private val clientOptions: ClientOpt val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "group", params.getPathParam(0)) + .addPathSegments("v1", "group", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepare(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/OrganizationServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/OrganizationServiceImpl.kt index b6af330b..ea53c72a 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/OrganizationServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/OrganizationServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,10 +15,10 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Organization import com.braintrustdata.api.models.OrganizationDeleteParams import com.braintrustdata.api.models.OrganizationListPage +import com.braintrustdata.api.models.OrganizationListPageResponse import com.braintrustdata.api.models.OrganizationListParams import com.braintrustdata.api.models.OrganizationRetrieveParams import com.braintrustdata.api.models.OrganizationUpdateParams @@ -68,7 +69,7 @@ class OrganizationServiceImpl internal constructor(private val clientOptions: Cl class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : OrganizationService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val members: MemberService.WithRawResponse by lazy { MemberServiceImpl.WithRawResponseImpl(clientOptions) @@ -86,7 +87,7 @@ class OrganizationServiceImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "organization", params.getPathParam(0)) + .addPathSegments("v1", "organization", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -112,7 +113,7 @@ class OrganizationServiceImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "organization", params.getPathParam(0)) + .addPathSegments("v1", "organization", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -129,8 +130,8 @@ class OrganizationServiceImpl internal constructor(private val clientOptions: Cl } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -154,7 +155,11 @@ class OrganizationServiceImpl internal constructor(private val clientOptions: Cl } } .let { - OrganizationListPage.of(OrganizationServiceImpl(clientOptions), params, it) + OrganizationListPage.builder() + .service(OrganizationServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -169,7 +174,7 @@ class OrganizationServiceImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "organization", params.getPathParam(0)) + .addPathSegments("v1", "organization", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepare(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectScoreServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectScoreServiceImpl.kt index ec7b0393..78c4f8ce 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectScoreServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectScoreServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.ProjectScore import com.braintrustdata.api.models.ProjectScoreCreateParams import com.braintrustdata.api.models.ProjectScoreDeleteParams import com.braintrustdata.api.models.ProjectScoreListPage +import com.braintrustdata.api.models.ProjectScoreListPageResponse import com.braintrustdata.api.models.ProjectScoreListParams import com.braintrustdata.api.models.ProjectScoreReplaceParams import com.braintrustdata.api.models.ProjectScoreRetrieveParams @@ -78,7 +79,7 @@ class ProjectScoreServiceImpl internal constructor(private val clientOptions: Cl class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : ProjectScoreService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -117,7 +118,7 @@ class ProjectScoreServiceImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "project_score", params.getPathParam(0)) + .addPathSegments("v1", "project_score", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -143,7 +144,7 @@ class ProjectScoreServiceImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "project_score", params.getPathParam(0)) + .addPathSegments("v1", "project_score", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -160,8 +161,8 @@ class ProjectScoreServiceImpl internal constructor(private val clientOptions: Cl } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -185,7 +186,11 @@ class ProjectScoreServiceImpl internal constructor(private val clientOptions: Cl } } .let { - ProjectScoreListPage.of(ProjectScoreServiceImpl(clientOptions), params, it) + ProjectScoreListPage.builder() + .service(ProjectScoreServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() } } } @@ -200,7 +205,7 @@ class ProjectScoreServiceImpl internal constructor(private val clientOptions: Cl val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "project_score", params.getPathParam(0)) + .addPathSegments("v1", "project_score", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepare(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectServiceImpl.kt index 502035c3..7ccbce80 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Project import com.braintrustdata.api.models.ProjectCreateParams import com.braintrustdata.api.models.ProjectDeleteParams import com.braintrustdata.api.models.ProjectListPage +import com.braintrustdata.api.models.ProjectListPageResponse import com.braintrustdata.api.models.ProjectListParams import com.braintrustdata.api.models.ProjectRetrieveParams import com.braintrustdata.api.models.ProjectUpdateParams @@ -61,7 +62,7 @@ class ProjectServiceImpl internal constructor(private val clientOptions: ClientO class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : ProjectService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val logs: LogService.WithRawResponse by lazy { LogServiceImpl.WithRawResponseImpl(clientOptions) @@ -106,7 +107,7 @@ class ProjectServiceImpl internal constructor(private val clientOptions: ClientO val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "project", params.getPathParam(0)) + .addPathSegments("v1", "project", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -132,7 +133,7 @@ class ProjectServiceImpl internal constructor(private val clientOptions: ClientO val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "project", params.getPathParam(0)) + .addPathSegments("v1", "project", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -149,8 +150,8 @@ class ProjectServiceImpl internal constructor(private val clientOptions: ClientO } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -173,7 +174,13 @@ class ProjectServiceImpl internal constructor(private val clientOptions: ClientO it.validate() } } - .let { ProjectListPage.of(ProjectServiceImpl(clientOptions), params, it) } + .let { + ProjectListPage.builder() + .service(ProjectServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } } @@ -187,7 +194,7 @@ class ProjectServiceImpl internal constructor(private val clientOptions: ClientO val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "project", params.getPathParam(0)) + .addPathSegments("v1", "project", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepare(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectTagServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectTagServiceImpl.kt index 79f8d590..17629219 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectTagServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectTagServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.ProjectTag import com.braintrustdata.api.models.ProjectTagCreateParams import com.braintrustdata.api.models.ProjectTagDeleteParams import com.braintrustdata.api.models.ProjectTagListPage +import com.braintrustdata.api.models.ProjectTagListPageResponse import com.braintrustdata.api.models.ProjectTagListParams import com.braintrustdata.api.models.ProjectTagReplaceParams import com.braintrustdata.api.models.ProjectTagRetrieveParams @@ -78,7 +79,7 @@ class ProjectTagServiceImpl internal constructor(private val clientOptions: Clie class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : ProjectTagService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -117,7 +118,7 @@ class ProjectTagServiceImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "project_tag", params.getPathParam(0)) + .addPathSegments("v1", "project_tag", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -143,7 +144,7 @@ class ProjectTagServiceImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "project_tag", params.getPathParam(0)) + .addPathSegments("v1", "project_tag", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -160,8 +161,8 @@ class ProjectTagServiceImpl internal constructor(private val clientOptions: Clie } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -184,7 +185,13 @@ class ProjectTagServiceImpl internal constructor(private val clientOptions: Clie it.validate() } } - .let { ProjectTagListPage.of(ProjectTagServiceImpl(clientOptions), params, it) } + .let { + ProjectTagListPage.builder() + .service(ProjectTagServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } } @@ -198,7 +205,7 @@ class ProjectTagServiceImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "project_tag", params.getPathParam(0)) + .addPathSegments("v1", "project_tag", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepare(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/PromptServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/PromptServiceImpl.kt index 7736249d..105c1629 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/PromptServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/PromptServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Prompt import com.braintrustdata.api.models.PromptCreateParams import com.braintrustdata.api.models.PromptDeleteParams import com.braintrustdata.api.models.PromptListPage +import com.braintrustdata.api.models.PromptListPageResponse import com.braintrustdata.api.models.PromptListParams import com.braintrustdata.api.models.PromptReplaceParams import com.braintrustdata.api.models.PromptRetrieveParams @@ -60,7 +61,7 @@ class PromptServiceImpl internal constructor(private val clientOptions: ClientOp class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : PromptService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -99,7 +100,7 @@ class PromptServiceImpl internal constructor(private val clientOptions: ClientOp val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "prompt", params.getPathParam(0)) + .addPathSegments("v1", "prompt", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -125,7 +126,7 @@ class PromptServiceImpl internal constructor(private val clientOptions: ClientOp val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "prompt", params.getPathParam(0)) + .addPathSegments("v1", "prompt", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -142,8 +143,8 @@ class PromptServiceImpl internal constructor(private val clientOptions: ClientOp } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -166,7 +167,13 @@ class PromptServiceImpl internal constructor(private val clientOptions: ClientOp it.validate() } } - .let { PromptListPage.of(PromptServiceImpl(clientOptions), params, it) } + .let { + PromptListPage.builder() + .service(PromptServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } } @@ -180,7 +187,7 @@ class PromptServiceImpl internal constructor(private val clientOptions: ClientOp val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "prompt", params.getPathParam(0)) + .addPathSegments("v1", "prompt", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepare(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/RoleServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/RoleServiceImpl.kt index 8c0a69cb..12949e33 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/RoleServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/RoleServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.Role import com.braintrustdata.api.models.RoleCreateParams import com.braintrustdata.api.models.RoleDeleteParams import com.braintrustdata.api.models.RoleListPage +import com.braintrustdata.api.models.RoleListPageResponse import com.braintrustdata.api.models.RoleListParams import com.braintrustdata.api.models.RoleReplaceParams import com.braintrustdata.api.models.RoleRetrieveParams @@ -59,7 +60,7 @@ class RoleServiceImpl internal constructor(private val clientOptions: ClientOpti class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : RoleService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -98,7 +99,7 @@ class RoleServiceImpl internal constructor(private val clientOptions: ClientOpti val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "role", params.getPathParam(0)) + .addPathSegments("v1", "role", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -124,7 +125,7 @@ class RoleServiceImpl internal constructor(private val clientOptions: ClientOpti val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "role", params.getPathParam(0)) + .addPathSegments("v1", "role", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -141,8 +142,8 @@ class RoleServiceImpl internal constructor(private val clientOptions: ClientOpti } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -165,7 +166,13 @@ class RoleServiceImpl internal constructor(private val clientOptions: ClientOpti it.validate() } } - .let { RoleListPage.of(RoleServiceImpl(clientOptions), params, it) } + .let { + RoleListPage.builder() + .service(RoleServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } } @@ -179,7 +186,7 @@ class RoleServiceImpl internal constructor(private val clientOptions: ClientOpti val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "role", params.getPathParam(0)) + .addPathSegments("v1", "role", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepare(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/SpanIframeServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/SpanIframeServiceImpl.kt index 33029900..d094ddea 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/SpanIframeServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/SpanIframeServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.SpanIFrame import com.braintrustdata.api.models.SpanIframeCreateParams import com.braintrustdata.api.models.SpanIframeDeleteParams import com.braintrustdata.api.models.SpanIframeListPage +import com.braintrustdata.api.models.SpanIframeListPageResponse import com.braintrustdata.api.models.SpanIframeListParams import com.braintrustdata.api.models.SpanIframeReplaceParams import com.braintrustdata.api.models.SpanIframeRetrieveParams @@ -78,7 +79,7 @@ class SpanIframeServiceImpl internal constructor(private val clientOptions: Clie class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : SpanIframeService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -117,7 +118,7 @@ class SpanIframeServiceImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "span_iframe", params.getPathParam(0)) + .addPathSegments("v1", "span_iframe", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -143,7 +144,7 @@ class SpanIframeServiceImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "span_iframe", params.getPathParam(0)) + .addPathSegments("v1", "span_iframe", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -160,8 +161,8 @@ class SpanIframeServiceImpl internal constructor(private val clientOptions: Clie } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -184,7 +185,13 @@ class SpanIframeServiceImpl internal constructor(private val clientOptions: Clie it.validate() } } - .let { SpanIframeListPage.of(SpanIframeServiceImpl(clientOptions), params, it) } + .let { + SpanIframeListPage.builder() + .service(SpanIframeServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } } @@ -198,7 +205,7 @@ class SpanIframeServiceImpl internal constructor(private val clientOptions: Clie val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "span_iframe", params.getPathParam(0)) + .addPathSegments("v1", "span_iframe", params._pathParam(0)) .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() .prepare(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/TopLevelServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/TopLevelServiceImpl.kt index 2bee0c27..44401cd1 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/TopLevelServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/TopLevelServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.stringHandler @@ -13,7 +14,6 @@ import com.braintrustdata.api.core.http.HttpResponse.Handler import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.TopLevelHelloWorldParams class TopLevelServiceImpl internal constructor(private val clientOptions: ClientOptions) : @@ -35,7 +35,7 @@ class TopLevelServiceImpl internal constructor(private val clientOptions: Client class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : TopLevelService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val helloWorldHandler: Handler = stringHandler().withErrorHandler(errorHandler) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/UserServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/UserServiceImpl.kt index 08e5047d..ade1f669 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/UserServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/UserServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -13,9 +14,9 @@ import com.braintrustdata.api.core.http.HttpResponse.Handler import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.User import com.braintrustdata.api.models.UserListPage +import com.braintrustdata.api.models.UserListPageResponse import com.braintrustdata.api.models.UserListParams import com.braintrustdata.api.models.UserRetrieveParams @@ -38,7 +39,7 @@ class UserServiceImpl internal constructor(private val clientOptions: ClientOpti class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : UserService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -50,7 +51,7 @@ class UserServiceImpl internal constructor(private val clientOptions: ClientOpti val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "user", params.getPathParam(0)) + .addPathSegments("v1", "user", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -66,8 +67,8 @@ class UserServiceImpl internal constructor(private val clientOptions: ClientOpti } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -90,7 +91,13 @@ class UserServiceImpl internal constructor(private val clientOptions: ClientOpti it.validate() } } - .let { UserListPage.of(UserServiceImpl(clientOptions), params, it) } + .let { + UserListPage.builder() + .service(UserServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ViewServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ViewServiceImpl.kt index 8c11e74f..823fa36e 100755 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ViewServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ViewServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,11 +15,11 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.View import com.braintrustdata.api.models.ViewCreateParams import com.braintrustdata.api.models.ViewDeleteParams import com.braintrustdata.api.models.ViewListPage +import com.braintrustdata.api.models.ViewListPageResponse import com.braintrustdata.api.models.ViewListParams import com.braintrustdata.api.models.ViewReplaceParams import com.braintrustdata.api.models.ViewRetrieveParams @@ -59,7 +60,7 @@ class ViewServiceImpl internal constructor(private val clientOptions: ClientOpti class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : ViewService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -98,7 +99,7 @@ class ViewServiceImpl internal constructor(private val clientOptions: ClientOpti val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "view", params.getPathParam(0)) + .addPathSegments("v1", "view", params._pathParam(0)) .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -124,7 +125,7 @@ class ViewServiceImpl internal constructor(private val clientOptions: ClientOpti val request = HttpRequest.builder() .method(HttpMethod.PATCH) - .addPathSegments("v1", "view", params.getPathParam(0)) + .addPathSegments("v1", "view", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -141,8 +142,8 @@ class ViewServiceImpl internal constructor(private val clientOptions: ClientOpti } } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) .withErrorHandler(errorHandler) override fun list( @@ -165,7 +166,13 @@ class ViewServiceImpl internal constructor(private val clientOptions: ClientOpti it.validate() } } - .let { ViewListPage.of(ViewServiceImpl(clientOptions), params, it) } + .let { + ViewListPage.builder() + .service(ViewServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } } @@ -179,7 +186,7 @@ class ViewServiceImpl internal constructor(private val clientOptions: ClientOpti val request = HttpRequest.builder() .method(HttpMethod.DELETE) - .addPathSegments("v1", "view", params.getPathParam(0)) + .addPathSegments("v1", "view", params._pathParam(0)) .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/organizations/MemberServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/organizations/MemberServiceImpl.kt index ffd783ac..df56e162 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/organizations/MemberServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/organizations/MemberServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking.organizations import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,7 +15,6 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.OrganizationMemberUpdateParams import com.braintrustdata.api.models.PatchOrganizationMembersOutput @@ -37,7 +37,7 @@ class MemberServiceImpl internal constructor(private val clientOptions: ClientOp class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : MemberService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/projects/LogServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/projects/LogServiceImpl.kt index d060fec8..ec5204b8 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/projects/LogServiceImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/projects/LogServiceImpl.kt @@ -3,6 +3,7 @@ package com.braintrustdata.api.services.blocking.projects import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.handlers.errorHandler import com.braintrustdata.api.core.handlers.jsonHandler @@ -14,7 +15,6 @@ import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.core.http.json import com.braintrustdata.api.core.http.parseable import com.braintrustdata.api.core.prepare -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.FeedbackResponseSchema import com.braintrustdata.api.models.FetchProjectLogsEventsResponse import com.braintrustdata.api.models.InsertEventsResponse @@ -62,7 +62,7 @@ class LogServiceImpl internal constructor(private val clientOptions: ClientOptio class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : LogService.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val feedbackHandler: Handler = jsonHandler(clientOptions.jsonMapper) @@ -75,7 +75,7 @@ class LogServiceImpl internal constructor(private val clientOptions: ClientOptio val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "feedback") + .addPathSegments("v1", "project_logs", params._pathParam(0), "feedback") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -103,7 +103,7 @@ class LogServiceImpl internal constructor(private val clientOptions: ClientOptio val request = HttpRequest.builder() .method(HttpMethod.GET) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "fetch") + .addPathSegments("v1", "project_logs", params._pathParam(0), "fetch") .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) @@ -130,7 +130,7 @@ class LogServiceImpl internal constructor(private val clientOptions: ClientOptio val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "fetch") + .addPathSegments("v1", "project_logs", params._pathParam(0), "fetch") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) @@ -158,7 +158,7 @@ class LogServiceImpl internal constructor(private val clientOptions: ClientOptio val request = HttpRequest.builder() .method(HttpMethod.POST) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "insert") + .addPathSegments("v1", "project_logs", params._pathParam(0), "insert") .body(json(clientOptions.jsonMapper, params._body())) .build() .prepare(clientOptions, params) diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/ObjectMappersTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/ObjectMappersTest.kt new file mode 100644 index 00000000..b1a6e835 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/ObjectMappersTest.kt @@ -0,0 +1,102 @@ +package com.braintrustdata.api.core + +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.exc.MismatchedInputException +import com.fasterxml.jackson.module.kotlin.readValue +import java.time.LocalDateTime +import kotlin.reflect.KClass +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.catchThrowable +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertDoesNotThrow +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource +import org.junitpioneer.jupiter.cartesian.CartesianTest + +internal class ObjectMappersTest { + + internal class ClassWithBooleanFieldPrefixedWithIs(private val isActive: JsonField) { + + @JsonProperty("is_active") @ExcludeMissing fun _isActive() = isActive + } + + @Test + fun write_whenFieldPrefixedWithIs_keepsPrefix() { + val value = ClassWithBooleanFieldPrefixedWithIs(JsonField.of(true)) + + val json = jsonMapper().writeValueAsString(value) + + assertThat(json).isEqualTo("{\"is_active\":true}") + } + + internal class Class(@get:JsonProperty("field") @JsonProperty("field") val field: String) + + enum class ShapeTestCase(val value: Any, val kClass: KClass<*>) { + STRING("Hello World!", String::class), + BOOLEAN(true, Boolean::class), + FLOAT(3.14F, Float::class), + DOUBLE(3.14, Double::class), + INTEGER(42, Int::class), + LONG(42L, Long::class), + MAP(mapOf("property" to "value"), Map::class), + CLASS(Class("Hello World!"), Class::class), + LIST(listOf(1, 2, 3), List::class); + + companion object { + val VALID_CONVERSIONS = + listOf( + FLOAT to DOUBLE, + FLOAT to INTEGER, + FLOAT to LONG, + DOUBLE to FLOAT, + DOUBLE to INTEGER, + DOUBLE to LONG, + INTEGER to FLOAT, + INTEGER to DOUBLE, + INTEGER to LONG, + LONG to FLOAT, + LONG to DOUBLE, + LONG to INTEGER, + CLASS to MAP, + // These aren't actually valid, but coercion configs don't work for String until + // v2.14.0: https://github.com/FasterXML/jackson-databind/issues/3240 + // We currently test on v2.13.4. + BOOLEAN to STRING, + FLOAT to STRING, + DOUBLE to STRING, + INTEGER to STRING, + LONG to STRING, + ) + } + } + + @CartesianTest + fun read(@CartesianTest.Enum shape1: ShapeTestCase, @CartesianTest.Enum shape2: ShapeTestCase) { + val jsonMapper = jsonMapper() + val json = jsonMapper.writeValueAsString(shape1.value) + + val e = catchThrowable { jsonMapper.readValue(json, shape2.kClass.java) } + + if (shape1 == shape2 || shape1 to shape2 in ShapeTestCase.VALID_CONVERSIONS) { + assertThat(e).isNull() + } else { + assertThat(e).isInstanceOf(MismatchedInputException::class.java) + } + } + + enum class LenientLocalDateTimeTestCase(val string: String) { + DATE("1998-04-21"), + DATE_TIME("1998-04-21T04:00:00"), + ZONED_DATE_TIME_1("1998-04-21T04:00:00+03:00"), + ZONED_DATE_TIME_2("1998-04-21T04:00:00Z"), + } + + @ParameterizedTest + @EnumSource + fun readLocalDateTime_lenient(testCase: LenientLocalDateTimeTestCase) { + val jsonMapper = jsonMapper() + val json = jsonMapper.writeValueAsString(testCase.string) + + assertDoesNotThrow { jsonMapper().readValue(json) } + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/PhantomReachableTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/PhantomReachableTest.kt index a7a9b514..787e3b1f 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/PhantomReachableTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/PhantomReachableTest.kt @@ -20,7 +20,7 @@ internal class PhantomReachableTest { assertThat(closed).isFalse() System.gc() - Thread.sleep(3000) + Thread.sleep(100) assertThat(closed).isTrue() } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/HeadersTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/HeadersTest.kt index 2a5ed57a..a4e77e29 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/HeadersTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/HeadersTest.kt @@ -1,8 +1,6 @@ package com.braintrustdata.api.core.http import org.assertj.core.api.Assertions.assertThat -import org.assertj.core.api.Assertions.catchThrowable -import org.assertj.core.api.Assumptions.assumeThat import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.EnumSource @@ -241,34 +239,4 @@ internal class HeadersTest { assertThat(size).isEqualTo(testCase.expectedSize) } - - @ParameterizedTest - @EnumSource - fun namesAreImmutable(testCase: TestCase) { - val headers = testCase.headers - val headerNamesCopy = headers.names().toSet() - - val throwable = catchThrowable { - (headers.names() as MutableSet).add("another name") - } - - assertThat(throwable).isInstanceOf(UnsupportedOperationException::class.java) - assertThat(headers.names()).isEqualTo(headerNamesCopy) - } - - @ParameterizedTest - @EnumSource - fun valuesAreImmutable(testCase: TestCase) { - val headers = testCase.headers - assumeThat(headers.size).isNotEqualTo(0) - val name = headers.names().first() - val headerValuesCopy = headers.values(name).toList() - - val throwable = catchThrowable { - (headers.values(name) as MutableList).add("another value") - } - - assertThat(throwable).isInstanceOf(UnsupportedOperationException::class.java) - assertThat(headers.values(name)).isEqualTo(headerValuesCopy) - } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/QueryParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/QueryParamsTest.kt index 08e55c66..0fd285c1 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/QueryParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/QueryParamsTest.kt @@ -1,8 +1,6 @@ package com.braintrustdata.api.core.http import org.assertj.core.api.Assertions.assertThat -import org.assertj.core.api.Assertions.catchThrowable -import org.assertj.core.api.Assumptions.assumeThat import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.EnumSource @@ -179,34 +177,4 @@ internal class QueryParamsTest { assertThat(size).isEqualTo(testCase.expectedSize) } - - @ParameterizedTest - @EnumSource - fun keysAreImmutable(testCase: TestCase) { - val queryParams = testCase.queryParams - val queryParamKeysCopy = queryParams.keys().toSet() - - val throwable = catchThrowable { - (queryParams.keys() as MutableSet).add("another key") - } - - assertThat(throwable).isInstanceOf(UnsupportedOperationException::class.java) - assertThat(queryParams.keys()).isEqualTo(queryParamKeysCopy) - } - - @ParameterizedTest - @EnumSource - fun valuesAreImmutable(testCase: TestCase) { - val queryParams = testCase.queryParams - assumeThat(queryParams.size).isNotEqualTo(0) - val key = queryParams.keys().first() - val queryParamValuesCopy = queryParams.values(key).toList() - - val throwable = catchThrowable { - (queryParams.values(key) as MutableList).add("another value") - } - - assertThat(throwable).isInstanceOf(UnsupportedOperationException::class.java) - assertThat(queryParams.values(key)).isEqualTo(queryParamValuesCopy) - } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/RetryingHttpClientTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/RetryingHttpClientTest.kt index d538b9b3..cb68648b 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/RetryingHttpClientTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/RetryingHttpClientTest.kt @@ -7,13 +7,16 @@ import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo import com.github.tomakehurst.wiremock.junit5.WireMockTest import com.github.tomakehurst.wiremock.stubbing.Scenario import java.io.InputStream +import java.time.Duration import java.util.concurrent.CompletableFuture import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.parallel.ResourceLock import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource @WireMockTest +@ResourceLock("https://github.com/wiremock/wiremock/issues/169") internal class RetryingHttpClientTest { private var openResponseCount = 0 @@ -24,6 +27,7 @@ internal class RetryingHttpClientTest { val okHttpClient = OkHttpClient.builder().baseUrl(wmRuntimeInfo.httpBaseUrl).build() httpClient = object : HttpClient { + override fun execute( request: HttpRequest, requestOptions: RequestOptions, @@ -40,6 +44,7 @@ internal class RetryingHttpClientTest { private fun trackClose(response: HttpResponse): HttpResponse { openResponseCount++ return object : HttpResponse { + private var isClosed = false override fun statusCode(): Int = response.statusCode() @@ -66,7 +71,7 @@ internal class RetryingHttpClientTest { @ValueSource(booleans = [false, true]) fun execute(async: Boolean) { stubFor(post(urlPathEqualTo("/something")).willReturn(ok())) - val retryingClient = RetryingHttpClient.builder().httpClient(httpClient).build() + val retryingClient = retryingHttpClientBuilder().build() val response = retryingClient.execute( @@ -88,11 +93,7 @@ internal class RetryingHttpClientTest { .willReturn(ok()) ) val retryingClient = - RetryingHttpClient.builder() - .httpClient(httpClient) - .maxRetries(2) - .idempotencyHeader("X-Some-Header") - .build() + retryingHttpClientBuilder().maxRetries(2).idempotencyHeader("X-Some-Header").build() val response = retryingClient.execute( @@ -134,8 +135,7 @@ internal class RetryingHttpClientTest { .willReturn(ok()) .willSetStateTo("COMPLETED") ) - val retryingClient = - RetryingHttpClient.builder().httpClient(httpClient).maxRetries(2).build() + val retryingClient = retryingHttpClientBuilder().maxRetries(2).build() val response = retryingClient.execute( @@ -181,8 +181,7 @@ internal class RetryingHttpClientTest { .willReturn(ok()) .willSetStateTo("COMPLETED") ) - val retryingClient = - RetryingHttpClient.builder().httpClient(httpClient).maxRetries(2).build() + val retryingClient = retryingHttpClientBuilder().maxRetries(2).build() val response = retryingClient.execute( @@ -220,8 +219,7 @@ internal class RetryingHttpClientTest { .willReturn(ok()) .willSetStateTo("COMPLETED") ) - val retryingClient = - RetryingHttpClient.builder().httpClient(httpClient).maxRetries(1).build() + val retryingClient = retryingHttpClientBuilder().maxRetries(1).build() val response = retryingClient.execute( @@ -234,6 +232,20 @@ internal class RetryingHttpClientTest { assertNoResponseLeaks() } + private fun retryingHttpClientBuilder() = + RetryingHttpClient.builder() + .httpClient(httpClient) + // Use a no-op `Sleeper` to make the test fast. + .sleeper( + object : RetryingHttpClient.Sleeper { + + override fun sleep(duration: Duration) {} + + override fun sleepAsync(duration: Duration): CompletableFuture = + CompletableFuture.completedFuture(null) + } + ) + private fun HttpClient.execute(request: HttpRequest, async: Boolean): HttpResponse = if (async) executeAsync(request).get() else execute(request) diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/SerializerTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/SerializerTest.kt deleted file mode 100755 index 824c8711..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/SerializerTest.kt +++ /dev/null @@ -1,99 +0,0 @@ -package com.braintrustdata.api.core.http - -import com.braintrustdata.api.core.* -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import java.util.* -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -internal class SerializerTest { - @JsonDeserialize(builder = ClassWithBooleanFieldPrefixedWithIs.Builder::class) - @NoAutoDetect - class ClassWithBooleanFieldPrefixedWithIs - private constructor( - private val isActive: JsonField, - private val additionalProperties: Map, - ) { - private var validated: Boolean = false - - private var hashCode: Int = 0 - - fun isActive(): Boolean? = isActive.getNullable("is_active") - - @JsonProperty("is_active") @ExcludeMissing fun _isActive() = isActive - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate() = apply { - if (!validated) { - isActive() - validated = true - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ClassWithBooleanFieldPrefixedWithIs && - isActive == other.isActive && - additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(isActive, additionalProperties) - } - return hashCode - } - - override fun toString() = - "MyClass{isActive=$isActive, additionalProperties=$additionalProperties}" - - companion object { - fun builder() = Builder() - } - - @NoAutoDetect - class Builder internal constructor() { - - private var isActive: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - fun isActive(isActive: Boolean) = isActive(JsonField.of(isActive)) - - @JsonProperty("is_active") - @ExcludeMissing - fun isActive(isActive: JsonField) = apply { this.isActive = isActive } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun build(): ClassWithBooleanFieldPrefixedWithIs = - ClassWithBooleanFieldPrefixedWithIs(isActive, additionalProperties.toImmutable()) - } - } - - @Test - fun serializeBooleanPrefixedWithIs() { - val value = ClassWithBooleanFieldPrefixedWithIs.builder().isActive(true).build() - assertThat(jsonMapper().writeValueAsString(value)).isEqualTo("{\"is_active\":true}") - } -} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AISecretTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AISecretTest.kt index d7241b89..32bc9fc5 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AISecretTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AISecretTest.kt @@ -3,6 +3,8 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -10,7 +12,7 @@ import org.junit.jupiter.api.Test internal class AISecretTest { @Test - fun createAISecret() { + fun create() { val aiSecret = AISecret.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -26,7 +28,7 @@ internal class AISecretTest { .type("type") .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) .build() - assertThat(aiSecret).isNotNull + assertThat(aiSecret.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(aiSecret.name()).isEqualTo("name") assertThat(aiSecret.orgId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -41,4 +43,32 @@ internal class AISecretTest { assertThat(aiSecret.type()).contains("type") assertThat(aiSecret.updatedAt()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val aiSecret = + AISecret.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .metadata( + AISecret.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .previewSecret("preview_secret") + .type("type") + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + + val roundtrippedAiSecret = + jsonMapper.readValue( + jsonMapper.writeValueAsString(aiSecret), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAiSecret).isEqualTo(aiSecret) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclBatchUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclBatchUpdateParamsTest.kt index fefded29..c59b1e7a 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclBatchUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclBatchUpdateParamsTest.kt @@ -2,7 +2,7 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -66,34 +66,29 @@ internal class AclBatchUpdateParamsTest { val body = params._body() - assertNotNull(body) - assertThat(body.addAcls()) - .contains( - listOf( - AclBatchUpdateParams.AddAcl.builder() - .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .objectType(AclObjectType.ORGANIZATION) - .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .permission(Permission.CREATE) - .restrictObjectType(AclObjectType.ORGANIZATION) - .roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - ) + assertThat(body.addAcls().getOrNull()) + .containsExactly( + AclBatchUpdateParams.AddAcl.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() ) - assertThat(body.removeAcls()) - .contains( - listOf( - AclBatchUpdateParams.RemoveAcl.builder() - .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .objectType(AclObjectType.ORGANIZATION) - .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .permission(Permission.CREATE) - .restrictObjectType(AclObjectType.ORGANIZATION) - .roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - ) + assertThat(body.removeAcls().getOrNull()) + .containsExactly( + AclBatchUpdateParams.RemoveAcl.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() ) } @@ -102,7 +97,5 @@ internal class AclBatchUpdateParamsTest { val params = AclBatchUpdateParams.builder().build() val body = params._body() - - assertNotNull(body) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclBatchUpdateResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclBatchUpdateResponseTest.kt index b04bfa85..e414f12a 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclBatchUpdateResponseTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclBatchUpdateResponseTest.kt @@ -2,6 +2,8 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -9,7 +11,7 @@ import org.junit.jupiter.api.Test internal class AclBatchUpdateResponseTest { @Test - fun createAclBatchUpdateResponse() { + fun create() { val aclBatchUpdateResponse = AclBatchUpdateResponse.builder() .addAddedAcl( @@ -41,7 +43,7 @@ internal class AclBatchUpdateResponseTest { .build() ) .build() - assertThat(aclBatchUpdateResponse).isNotNull + assertThat(aclBatchUpdateResponse.addedAcls()) .containsExactly( Acl.builder() @@ -73,4 +75,48 @@ internal class AclBatchUpdateResponseTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val aclBatchUpdateResponse = + AclBatchUpdateResponse.builder() + .addAddedAcl( + Acl.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + ._objectOrgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .addRemovedAcl( + Acl.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + ._objectOrgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + val roundtrippedAclBatchUpdateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(aclBatchUpdateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAclBatchUpdateResponse).isEqualTo(aclBatchUpdateResponse) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclCreateParamsTest.kt index 20eb299f..8076e142 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclCreateParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -36,7 +35,6 @@ internal class AclCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) assertThat(body.groupId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -56,7 +54,6 @@ internal class AclCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclDeleteParamsTest.kt index a520f8ce..3f7c31e8 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclDeleteParamsTest.kt @@ -13,12 +13,11 @@ internal class AclDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = AclDeleteParams.builder().aclId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "aclId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclFindAndDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclFindAndDeleteParamsTest.kt index d6b03177..3185f02a 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclFindAndDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclFindAndDeleteParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -36,7 +35,6 @@ internal class AclFindAndDeleteParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) assertThat(body.groupId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -56,7 +54,6 @@ internal class AclFindAndDeleteParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclListPageResponseTest.kt new file mode 100644 index 00000000..fdb2fe1a --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclListPageResponseTest.kt @@ -0,0 +1,79 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AclListPageResponseTest { + + @Test + fun create() { + val aclListPageResponse = + AclListPageResponse.builder() + .addObject( + Acl.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + ._objectOrgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + assertThat(aclListPageResponse.objects()) + .containsExactly( + Acl.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + ._objectOrgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val aclListPageResponse = + AclListPageResponse.builder() + .addObject( + Acl.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + ._objectOrgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + val roundtrippedAclListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(aclListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAclListPageResponse).isEqualTo(aclListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclRetrieveParamsTest.kt index 8ad3dfac..0dc6c6be 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclRetrieveParamsTest.kt @@ -13,13 +13,12 @@ internal class AclRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = AclRetrieveParams.builder().aclId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "aclId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclTest.kt index 39258080..862ff24d 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclTest.kt @@ -2,6 +2,8 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -9,7 +11,7 @@ import org.junit.jupiter.api.Test internal class AclTest { @Test - fun createAcl() { + fun create() { val acl = Acl.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -23,7 +25,7 @@ internal class AclTest { .roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(acl).isNotNull + assertThat(acl.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(acl._objectOrgId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(acl.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -35,4 +37,27 @@ internal class AclTest { assertThat(acl.roleId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(acl.userId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val acl = + Acl.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + ._objectOrgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val roundtrippedAcl = + jsonMapper.readValue(jsonMapper.writeValueAsString(acl), jacksonTypeRef()) + + assertThat(roundtrippedAcl).isEqualTo(acl) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretCreateParamsTest.kt index d91d0d19..a3115935 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretCreateParamsTest.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -41,7 +40,6 @@ internal class AiSecretCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.metadata()) .contains( @@ -60,7 +58,6 @@ internal class AiSecretCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretDeleteParamsTest.kt index 2d9d6f3a..0aecaacb 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretDeleteParamsTest.kt @@ -13,15 +13,14 @@ internal class AiSecretDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = AiSecretDeleteParams.builder() .aiSecretId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "aiSecretId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretFindAndDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretFindAndDeleteParamsTest.kt index d7365a0b..7e72a927 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretFindAndDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretFindAndDeleteParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -19,7 +18,6 @@ internal class AiSecretFindAndDeleteParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.orgName()).contains("org_name") } @@ -30,7 +28,6 @@ internal class AiSecretFindAndDeleteParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretListPageResponseTest.kt new file mode 100644 index 00000000..f37f7b6c --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretListPageResponseTest.kt @@ -0,0 +1,86 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AiSecretListPageResponseTest { + + @Test + fun create() { + val aiSecretListPageResponse = + AiSecretListPageResponse.builder() + .addObject( + AISecret.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .metadata( + AISecret.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .previewSecret("preview_secret") + .type("type") + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + ) + .build() + + assertThat(aiSecretListPageResponse.objects()) + .containsExactly( + AISecret.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .metadata( + AISecret.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .previewSecret("preview_secret") + .type("type") + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val aiSecretListPageResponse = + AiSecretListPageResponse.builder() + .addObject( + AISecret.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .metadata( + AISecret.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .previewSecret("preview_secret") + .type("type") + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + ) + .build() + + val roundtrippedAiSecretListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(aiSecretListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAiSecretListPageResponse).isEqualTo(aiSecretListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretReplaceParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretReplaceParamsTest.kt index cde09c24..4f3b98f1 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretReplaceParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretReplaceParamsTest.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -41,7 +40,6 @@ internal class AiSecretReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.metadata()) .contains( @@ -60,7 +58,6 @@ internal class AiSecretReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretRetrieveParamsTest.kt index a9f2f2aa..6fa5c828 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretRetrieveParamsTest.kt @@ -13,15 +13,14 @@ internal class AiSecretRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = AiSecretRetrieveParams.builder() .aiSecretId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "aiSecretId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretUpdateParamsTest.kt index 627ea2bf..27e6e879 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretUpdateParamsTest.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -24,6 +23,18 @@ internal class AiSecretUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = + AiSecretUpdateParams.builder() + .aiSecretId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -41,7 +52,6 @@ internal class AiSecretUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.metadata()) .contains( AiSecretUpdateParams.Metadata.builder() @@ -61,20 +71,5 @@ internal class AiSecretUpdateParamsTest { .build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - AiSecretUpdateParams.builder() - .aiSecretId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - assertThat(params).isNotNull - // path param "aiSecretId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyCreateParamsTest.kt index 315dc13b..ef31b0d6 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyCreateParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -19,7 +18,6 @@ internal class ApiKeyCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.orgName()).contains("org_name") } @@ -30,7 +28,6 @@ internal class ApiKeyCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyDeleteParamsTest.kt index f7546c55..4172b7c4 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyDeleteParamsTest.kt @@ -13,13 +13,12 @@ internal class ApiKeyDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = ApiKeyDeleteParams.builder().apiKeyId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "apiKeyId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyListPageResponseTest.kt new file mode 100644 index 00000000..396312d3 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyListPageResponseTest.kt @@ -0,0 +1,67 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ApiKeyListPageResponseTest { + + @Test + fun create() { + val apiKeyListPageResponse = + ApiKeyListPageResponse.builder() + .addObject( + ApiKey.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .previewName("preview_name") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + assertThat(apiKeyListPageResponse.objects()) + .containsExactly( + ApiKey.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .previewName("preview_name") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val apiKeyListPageResponse = + ApiKeyListPageResponse.builder() + .addObject( + ApiKey.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .previewName("preview_name") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + val roundtrippedApiKeyListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(apiKeyListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedApiKeyListPageResponse).isEqualTo(apiKeyListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyRetrieveParamsTest.kt index f5ca88f6..1612ee3b 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyRetrieveParamsTest.kt @@ -13,13 +13,12 @@ internal class ApiKeyRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = ApiKeyRetrieveParams.builder().apiKeyId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "apiKeyId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyTest.kt index 099b0e65..0bda4c73 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyTest.kt @@ -2,6 +2,8 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -9,7 +11,7 @@ import org.junit.jupiter.api.Test internal class ApiKeyTest { @Test - fun createApiKey() { + fun create() { val apiKey = ApiKey.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -19,7 +21,7 @@ internal class ApiKeyTest { .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(apiKey).isNotNull + assertThat(apiKey.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(apiKey.name()).isEqualTo("name") assertThat(apiKey.previewName()).isEqualTo("preview_name") @@ -27,4 +29,23 @@ internal class ApiKeyTest { assertThat(apiKey.orgId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(apiKey.userId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val apiKey = + ApiKey.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .previewName("preview_name") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val roundtrippedApiKey = + jsonMapper.readValue(jsonMapper.writeValueAsString(apiKey), jacksonTypeRef()) + + assertThat(roundtrippedApiKey).isEqualTo(apiKey) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartImageTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartImageTest.kt index b826be89..ccce4723 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartImageTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartImageTest.kt @@ -2,13 +2,15 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class ChatCompletionContentPartImageTest { @Test - fun createChatCompletionContentPartImage() { + fun create() { val chatCompletionContentPartImage = ChatCompletionContentPartImage.builder() .imageUrl( @@ -19,7 +21,7 @@ internal class ChatCompletionContentPartImageTest { ) .type(ChatCompletionContentPartImage.Type.IMAGE_URL) .build() - assertThat(chatCompletionContentPartImage).isNotNull + assertThat(chatCompletionContentPartImage.imageUrl()) .isEqualTo( ChatCompletionContentPartImage.ImageUrl.builder() @@ -30,4 +32,28 @@ internal class ChatCompletionContentPartImageTest { assertThat(chatCompletionContentPartImage.type()) .isEqualTo(ChatCompletionContentPartImage.Type.IMAGE_URL) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val chatCompletionContentPartImage = + ChatCompletionContentPartImage.builder() + .imageUrl( + ChatCompletionContentPartImage.ImageUrl.builder() + .url("url") + .detail(ChatCompletionContentPartImage.ImageUrl.Detail.AUTO) + .build() + ) + .type(ChatCompletionContentPartImage.Type.IMAGE_URL) + .build() + + val roundtrippedChatCompletionContentPartImage = + jsonMapper.readValue( + jsonMapper.writeValueAsString(chatCompletionContentPartImage), + jacksonTypeRef(), + ) + + assertThat(roundtrippedChatCompletionContentPartImage) + .isEqualTo(chatCompletionContentPartImage) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartTextTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartTextTest.kt index 2e8d9c23..23dea46b 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartTextTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartTextTest.kt @@ -2,21 +2,42 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class ChatCompletionContentPartTextTest { @Test - fun createChatCompletionContentPartText() { + fun create() { val chatCompletionContentPartText = ChatCompletionContentPartText.builder() .type(ChatCompletionContentPartText.Type.TEXT) .text("text") .build() - assertThat(chatCompletionContentPartText).isNotNull + assertThat(chatCompletionContentPartText.type()) .isEqualTo(ChatCompletionContentPartText.Type.TEXT) assertThat(chatCompletionContentPartText.text()).contains("text") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val chatCompletionContentPartText = + ChatCompletionContentPartText.builder() + .type(ChatCompletionContentPartText.Type.TEXT) + .text("text") + .build() + + val roundtrippedChatCompletionContentPartText = + jsonMapper.readValue( + jsonMapper.writeValueAsString(chatCompletionContentPartText), + jacksonTypeRef(), + ) + + assertThat(roundtrippedChatCompletionContentPartText) + .isEqualTo(chatCompletionContentPartText) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ChatCompletionMessageToolCallTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ChatCompletionMessageToolCallTest.kt index b140cc39..4ff757fd 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ChatCompletionMessageToolCallTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ChatCompletionMessageToolCallTest.kt @@ -2,13 +2,15 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class ChatCompletionMessageToolCallTest { @Test - fun createChatCompletionMessageToolCall() { + fun create() { val chatCompletionMessageToolCall = ChatCompletionMessageToolCall.builder() .id("id") @@ -20,7 +22,7 @@ internal class ChatCompletionMessageToolCallTest { ) .type(ChatCompletionMessageToolCall.Type.FUNCTION) .build() - assertThat(chatCompletionMessageToolCall).isNotNull + assertThat(chatCompletionMessageToolCall.id()).isEqualTo("id") assertThat(chatCompletionMessageToolCall.function()) .isEqualTo( @@ -32,4 +34,29 @@ internal class ChatCompletionMessageToolCallTest { assertThat(chatCompletionMessageToolCall.type()) .isEqualTo(ChatCompletionMessageToolCall.Type.FUNCTION) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val chatCompletionMessageToolCall = + ChatCompletionMessageToolCall.builder() + .id("id") + .function( + ChatCompletionMessageToolCall.Function.builder() + .arguments("arguments") + .name("name") + .build() + ) + .type(ChatCompletionMessageToolCall.Type.FUNCTION) + .build() + + val roundtrippedChatCompletionMessageToolCall = + jsonMapper.readValue( + jsonMapper.writeValueAsString(chatCompletionMessageToolCall), + jacksonTypeRef(), + ) + + assertThat(roundtrippedChatCompletionMessageToolCall) + .isEqualTo(chatCompletionMessageToolCall) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/CodeBundleTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/CodeBundleTest.kt index 5eb775e3..e3df5465 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/CodeBundleTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/CodeBundleTest.kt @@ -2,13 +2,15 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class CodeBundleTest { @Test - fun createCodeBundle() { + fun create() { val codeBundle = CodeBundle.builder() .bundleId("bundle_id") @@ -31,7 +33,7 @@ internal class CodeBundleTest { ) .preview("preview") .build() - assertThat(codeBundle).isNotNull + assertThat(codeBundle.bundleId()).isEqualTo("bundle_id") assertThat(codeBundle.location()) .isEqualTo( @@ -56,4 +58,39 @@ internal class CodeBundleTest { ) assertThat(codeBundle.preview()).contains("preview") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val codeBundle = + CodeBundle.builder() + .bundleId("bundle_id") + .location( + CodeBundle.Location.Experiment.builder() + .evalName("eval_name") + .position( + CodeBundle.Location.Experiment.Position.Type.builder() + .type(CodeBundle.Location.Experiment.Position.Type.InnerType.TASK) + .build() + ) + .type(CodeBundle.Location.Experiment.Type.EXPERIMENT) + .build() + ) + .runtimeContext( + CodeBundle.RuntimeContext.builder() + .runtime(CodeBundle.RuntimeContext.Runtime.NODE) + .version("version") + .build() + ) + .preview("preview") + .build() + + val roundtrippedCodeBundle = + jsonMapper.readValue( + jsonMapper.writeValueAsString(codeBundle), + jacksonTypeRef(), + ) + + assertThat(roundtrippedCodeBundle).isEqualTo(codeBundle) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/CreateApiKeyOutputTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/CreateApiKeyOutputTest.kt index f9057687..931c2a7f 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/CreateApiKeyOutputTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/CreateApiKeyOutputTest.kt @@ -2,6 +2,8 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -9,7 +11,7 @@ import org.junit.jupiter.api.Test internal class CreateApiKeyOutputTest { @Test - fun createCreateApiKeyOutput() { + fun create() { val createApiKeyOutput = CreateApiKeyOutput.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -20,7 +22,7 @@ internal class CreateApiKeyOutputTest { .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(createApiKeyOutput).isNotNull + assertThat(createApiKeyOutput.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(createApiKeyOutput.key()).isEqualTo("key") assertThat(createApiKeyOutput.name()).isEqualTo("name") @@ -30,4 +32,27 @@ internal class CreateApiKeyOutputTest { assertThat(createApiKeyOutput.orgId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(createApiKeyOutput.userId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val createApiKeyOutput = + CreateApiKeyOutput.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .key("key") + .name("name") + .previewName("preview_name") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val roundtrippedCreateApiKeyOutput = + jsonMapper.readValue( + jsonMapper.writeValueAsString(createApiKeyOutput), + jacksonTypeRef(), + ) + + assertThat(roundtrippedCreateApiKeyOutput).isEqualTo(createApiKeyOutput) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/CrossObjectInsertResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/CrossObjectInsertResponseTest.kt index 4abcfb9d..efd9ee0d 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/CrossObjectInsertResponseTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/CrossObjectInsertResponseTest.kt @@ -3,13 +3,15 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class CrossObjectInsertResponseTest { @Test - fun createCrossObjectInsertResponse() { + fun create() { val crossObjectInsertResponse = CrossObjectInsertResponse.builder() .dataset( @@ -37,7 +39,7 @@ internal class CrossObjectInsertResponseTest { .build() ) .build() - assertThat(crossObjectInsertResponse).isNotNull + assertThat(crossObjectInsertResponse.dataset()) .contains( CrossObjectInsertResponse.Dataset.builder() @@ -66,4 +68,44 @@ internal class CrossObjectInsertResponseTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val crossObjectInsertResponse = + CrossObjectInsertResponse.builder() + .dataset( + CrossObjectInsertResponse.Dataset.builder() + .putAdditionalProperty( + "foo", + JsonValue.from(mapOf("row_ids" to listOf("string"))), + ) + .build() + ) + .experiment( + CrossObjectInsertResponse.Experiment.builder() + .putAdditionalProperty( + "foo", + JsonValue.from(mapOf("row_ids" to listOf("string"))), + ) + .build() + ) + .projectLogs( + CrossObjectInsertResponse.ProjectLogs.builder() + .putAdditionalProperty( + "foo", + JsonValue.from(mapOf("row_ids" to listOf("string"))), + ) + .build() + ) + .build() + + val roundtrippedCrossObjectInsertResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(crossObjectInsertResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedCrossObjectInsertResponse).isEqualTo(crossObjectInsertResponse) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DataSummaryTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DataSummaryTest.kt index f7759625..40a33b54 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DataSummaryTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DataSummaryTest.kt @@ -2,15 +2,31 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class DataSummaryTest { @Test - fun createDataSummary() { + fun create() { val dataSummary = DataSummary.builder().totalRecords(0L).build() - assertThat(dataSummary).isNotNull + assertThat(dataSummary.totalRecords()).isEqualTo(0L) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val dataSummary = DataSummary.builder().totalRecords(0L).build() + + val roundtrippedDataSummary = + jsonMapper.readValue( + jsonMapper.writeValueAsString(dataSummary), + jacksonTypeRef(), + ) + + assertThat(roundtrippedDataSummary).isEqualTo(dataSummary) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetCreateParamsTest.kt index e9bd56e1..117b3591 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetCreateParamsTest.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -39,7 +38,6 @@ internal class DatasetCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.description()).contains("description") @@ -61,7 +59,6 @@ internal class DatasetCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetDeleteParamsTest.kt index 1d74f765..87b85a35 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetDeleteParamsTest.kt @@ -13,13 +13,12 @@ internal class DatasetDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = DatasetDeleteParams.builder().datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "datasetId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetEventTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetEventTest.kt index 14d3a5c7..de13fd72 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetEventTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetEventTest.kt @@ -3,14 +3,17 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class DatasetEventTest { @Test - fun createDatasetEvent() { + fun create() { val datasetEvent = DatasetEvent.builder() .id("id") @@ -35,7 +38,7 @@ internal class DatasetEventTest { ) .addTag("string") .build() - assertThat(datasetEvent).isNotNull + assertThat(datasetEvent.id()).isEqualTo("id") assertThat(datasetEvent._xactId()).isEqualTo("_xact_id") assertThat(datasetEvent.created()) @@ -59,6 +62,43 @@ internal class DatasetEventTest { .created("created") .build() ) - assertThat(datasetEvent.tags().get()).containsExactly("string") + assertThat(datasetEvent.tags().getOrNull()).containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val datasetEvent = + DatasetEvent.builder() + .id("id") + ._xactId("_xact_id") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .rootSpanId("root_span_id") + .spanId("span_id") + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .isRoot(true) + .metadata(DatasetEvent.Metadata.builder().model("model").build()) + .origin( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + .addTag("string") + .build() + + val roundtrippedDatasetEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(datasetEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedDatasetEvent).isEqualTo(datasetEvent) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFeedbackParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFeedbackParamsTest.kt index 5c8d41e3..383af384 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFeedbackParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFeedbackParamsTest.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -29,6 +28,19 @@ internal class DatasetFeedbackParamsTest { .build() } + @Test + fun pathParams() { + val params = + DatasetFeedbackParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addFeedback(FeedbackDatasetItem.builder().id("id").build()) + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -51,22 +63,19 @@ internal class DatasetFeedbackParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.feedback()) - .isEqualTo( - listOf( - FeedbackDatasetItem.builder() - .id("id") - .comment("comment") - .metadata( - FeedbackDatasetItem.Metadata.builder() - .putAdditionalProperty("foo", JsonValue.from("bar")) - .build() - ) - .source(FeedbackDatasetItem.Source.APP) - .addTag("string") - .build() - ) + .containsExactly( + FeedbackDatasetItem.builder() + .id("id") + .comment("comment") + .metadata( + FeedbackDatasetItem.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .source(FeedbackDatasetItem.Source.APP) + .addTag("string") + .build() ) } @@ -80,22 +89,6 @@ internal class DatasetFeedbackParamsTest { val body = params._body() - assertNotNull(body) - assertThat(body.feedback()) - .isEqualTo(listOf(FeedbackDatasetItem.builder().id("id").build())) - } - - @Test - fun getPathParam() { - val params = - DatasetFeedbackParams.builder() - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .addFeedback(FeedbackDatasetItem.builder().id("id").build()) - .build() - assertThat(params).isNotNull - // path param "datasetId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(body.feedback()).containsExactly(FeedbackDatasetItem.builder().id("id").build()) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFetchParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFetchParamsTest.kt index 1c31fd85..79504f72 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFetchParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFetchParamsTest.kt @@ -19,6 +19,16 @@ internal class DatasetFetchParamsTest { .build() } + @Test + fun pathParams() { + val params = + DatasetFetchParams.builder().datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun queryParams() { val params = @@ -52,15 +62,4 @@ internal class DatasetFetchParamsTest { assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } - - @Test - fun getPathParam() { - val params = - DatasetFetchParams.builder().datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "datasetId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFetchPostParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFetchPostParamsTest.kt index 53eeec48..e3e09e9b 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFetchPostParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFetchPostParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -20,6 +19,18 @@ internal class DatasetFetchPostParamsTest { .build() } + @Test + fun pathParams() { + val params = + DatasetFetchPostParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -34,7 +45,6 @@ internal class DatasetFetchPostParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.cursor()).contains("cursor") assertThat(body.limit()).contains(0L) assertThat(body.maxRootSpanId()).contains("max_root_span_id") @@ -50,20 +60,5 @@ internal class DatasetFetchPostParamsTest { .build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - DatasetFetchPostParams.builder() - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - assertThat(params).isNotNull - // path param "datasetId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetInsertParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetInsertParamsTest.kt index 4b535b10..09847227 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetInsertParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetInsertParamsTest.kt @@ -4,7 +4,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue import java.time.OffsetDateTime -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -43,6 +42,19 @@ internal class DatasetInsertParamsTest { .build() } + @Test + fun pathParams() { + val params = + DatasetInsertParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addEvent(InsertDatasetEvent.builder().build()) + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -78,35 +90,32 @@ internal class DatasetInsertParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.events()) - .isEqualTo( - listOf( - InsertDatasetEvent.builder() - .id("id") - ._isMerge(true) - .addMergePath(listOf("string")) - ._objectDelete(true) - ._parentId("_parent_id") - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata(InsertDatasetEvent.Metadata.builder().model("model").build()) - .origin( - ObjectReference.builder() - .id("id") - ._xactId("_xact_id") - .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .objectType(ObjectReference.ObjectType.EXPERIMENT) - .created("created") - .build() - ) - .rootSpanId("root_span_id") - .spanId("span_id") - .addSpanParent("string") - .addTag("string") - .build() - ) + .containsExactly( + InsertDatasetEvent.builder() + .id("id") + ._isMerge(true) + .addMergePath(listOf("string")) + ._objectDelete(true) + ._parentId("_parent_id") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .metadata(InsertDatasetEvent.Metadata.builder().model("model").build()) + .origin( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + .rootSpanId("root_span_id") + .spanId("span_id") + .addSpanParent("string") + .addTag("string") + .build() ) } @@ -120,21 +129,6 @@ internal class DatasetInsertParamsTest { val body = params._body() - assertNotNull(body) - assertThat(body.events()).isEqualTo(listOf(InsertDatasetEvent.builder().build())) - } - - @Test - fun getPathParam() { - val params = - DatasetInsertParams.builder() - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .addEvent(InsertDatasetEvent.builder().build()) - .build() - assertThat(params).isNotNull - // path param "datasetId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(body.events()).containsExactly(InsertDatasetEvent.builder().build()) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetListPageResponseTest.kt new file mode 100644 index 00000000..af744573 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetListPageResponseTest.kt @@ -0,0 +1,86 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class DatasetListPageResponseTest { + + @Test + fun create() { + val datasetListPageResponse = + DatasetListPageResponse.builder() + .addObject( + Dataset.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .metadata( + Dataset.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + assertThat(datasetListPageResponse.objects()) + .containsExactly( + Dataset.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .metadata( + Dataset.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val datasetListPageResponse = + DatasetListPageResponse.builder() + .addObject( + Dataset.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .metadata( + Dataset.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + val roundtrippedDatasetListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(datasetListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedDatasetListPageResponse).isEqualTo(datasetListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetRetrieveParamsTest.kt index 147e6451..1cdff551 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetRetrieveParamsTest.kt @@ -13,15 +13,14 @@ internal class DatasetRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = DatasetRetrieveParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "datasetId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetSummarizeParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetSummarizeParamsTest.kt index 24bc6c0f..49062a2c 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetSummarizeParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetSummarizeParamsTest.kt @@ -16,6 +16,18 @@ internal class DatasetSummarizeParamsTest { .build() } + @Test + fun pathParams() { + val params = + DatasetSummarizeParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun queryParams() { val params = @@ -41,17 +53,4 @@ internal class DatasetSummarizeParamsTest { assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } - - @Test - fun getPathParam() { - val params = - DatasetSummarizeParams.builder() - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - assertThat(params).isNotNull - // path param "datasetId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetTest.kt index 5751efca..b46ed92a 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetTest.kt @@ -3,6 +3,8 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -10,7 +12,7 @@ import org.junit.jupiter.api.Test internal class DatasetTest { @Test - fun createDataset() { + fun create() { val dataset = Dataset.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -26,7 +28,7 @@ internal class DatasetTest { ) .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(dataset).isNotNull + assertThat(dataset.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(dataset.name()).isEqualTo("name") assertThat(dataset.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -41,4 +43,29 @@ internal class DatasetTest { ) assertThat(dataset.userId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val dataset = + Dataset.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .metadata( + Dataset.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val roundtrippedDataset = + jsonMapper.readValue(jsonMapper.writeValueAsString(dataset), jacksonTypeRef()) + + assertThat(roundtrippedDataset).isEqualTo(dataset) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetUpdateParamsTest.kt index ebdf0e4f..daee439a 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetUpdateParamsTest.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -23,6 +22,16 @@ internal class DatasetUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = + DatasetUpdateParams.builder().datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -39,7 +48,6 @@ internal class DatasetUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.description()).contains("description") assertThat(body.metadata()) .contains( @@ -56,18 +64,5 @@ internal class DatasetUpdateParamsTest { DatasetUpdateParams.builder().datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - DatasetUpdateParams.builder().datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "datasetId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarCreateParamsTest.kt index 1af40d88..fbb18ad2 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarCreateParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -30,7 +29,6 @@ internal class EnvVarCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.objectType()).isEqualTo(EnvVarCreateParams.ObjectType.ORGANIZATION) @@ -48,7 +46,6 @@ internal class EnvVarCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.objectType()).isEqualTo(EnvVarCreateParams.ObjectType.ORGANIZATION) diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarDeleteParamsTest.kt index e7c988b4..80887f78 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarDeleteParamsTest.kt @@ -13,13 +13,12 @@ internal class EnvVarDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = EnvVarDeleteParams.builder().envVarId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "envVarId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarListResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarListResponseTest.kt index 801245e2..d10c2868 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarListResponseTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarListResponseTest.kt @@ -2,6 +2,8 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -9,7 +11,7 @@ import org.junit.jupiter.api.Test internal class EnvVarListResponseTest { @Test - fun createEnvVarListResponse() { + fun create() { val envVarListResponse = EnvVarListResponse.builder() .addObject( @@ -23,7 +25,7 @@ internal class EnvVarListResponseTest { .build() ) .build() - assertThat(envVarListResponse).isNotNull + assertThat(envVarListResponse.objects()) .containsExactly( EnvVar.builder() @@ -36,4 +38,30 @@ internal class EnvVarListResponseTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val envVarListResponse = + EnvVarListResponse.builder() + .addObject( + EnvVar.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVar.ObjectType.ORGANIZATION) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .used(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + ) + .build() + + val roundtrippedEnvVarListResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(envVarListResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedEnvVarListResponse).isEqualTo(envVarListResponse) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarReplaceParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarReplaceParamsTest.kt index 74d5e35f..bb097933 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarReplaceParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarReplaceParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -30,7 +29,6 @@ internal class EnvVarReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.objectType()).isEqualTo(EnvVarReplaceParams.ObjectType.ORGANIZATION) @@ -48,7 +46,6 @@ internal class EnvVarReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.objectType()).isEqualTo(EnvVarReplaceParams.ObjectType.ORGANIZATION) diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarRetrieveParamsTest.kt index d2eee241..b3cefe22 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarRetrieveParamsTest.kt @@ -13,13 +13,12 @@ internal class EnvVarRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = EnvVarRetrieveParams.builder().envVarId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "envVarId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarTest.kt index 6df9126a..f046db47 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarTest.kt @@ -2,6 +2,8 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -9,7 +11,7 @@ import org.junit.jupiter.api.Test internal class EnvVarTest { @Test - fun createEnvVar() { + fun create() { val envVar = EnvVar.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -19,7 +21,7 @@ internal class EnvVarTest { .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) .used(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) .build() - assertThat(envVar).isNotNull + assertThat(envVar.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(envVar.name()).isEqualTo("name") assertThat(envVar.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -27,4 +29,23 @@ internal class EnvVarTest { assertThat(envVar.created()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) assertThat(envVar.used()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val envVar = + EnvVar.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVar.ObjectType.ORGANIZATION) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .used(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + + val roundtrippedEnvVar = + jsonMapper.readValue(jsonMapper.writeValueAsString(envVar), jacksonTypeRef()) + + assertThat(roundtrippedEnvVar).isEqualTo(envVar) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarUpdateParamsTest.kt index 81bdf42a..ec4c0edc 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarUpdateParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -18,46 +17,43 @@ internal class EnvVarUpdateParamsTest { } @Test - fun body() { + fun pathParams() { val params = EnvVarUpdateParams.builder() .envVarId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .name("name") - .value("value") .build() - val body = params._body() - - assertNotNull(body) - assertThat(body.name()).isEqualTo("name") - assertThat(body.value()).contains("value") + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") } @Test - fun bodyWithoutOptionalFields() { + fun body() { val params = EnvVarUpdateParams.builder() .envVarId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .name("name") + .value("value") .build() val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") + assertThat(body.value()).contains("value") } @Test - fun getPathParam() { + fun bodyWithoutOptionalFields() { val params = EnvVarUpdateParams.builder() .envVarId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .name("name") .build() - assertThat(params).isNotNull - // path param "envVarId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EvalCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EvalCreateParamsTest.kt index ec0f8d22..99ba29a1 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EvalCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EvalCreateParamsTest.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -173,7 +172,6 @@ internal class EvalCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.data()) .isEqualTo( EvalCreateParams.Data.ofDatasetId( @@ -190,14 +188,12 @@ internal class EvalCreateParamsTest { ) assertThat(body.projectId()).isEqualTo("project_id") assertThat(body.scores()) - .isEqualTo( - listOf( - EvalCreateParams.Score.ofFunctionId( - EvalCreateParams.Score.FunctionId.builder() - .functionId("function_id") - .version("version") - .build() - ) + .containsExactly( + EvalCreateParams.Score.ofFunctionId( + EvalCreateParams.Score.FunctionId.builder() + .functionId("function_id") + .version("version") + .build() ) ) assertThat(body.task()) @@ -283,7 +279,6 @@ internal class EvalCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.data()) .isEqualTo( EvalCreateParams.Data.ofDatasetId( @@ -292,13 +287,9 @@ internal class EvalCreateParamsTest { ) assertThat(body.projectId()).isEqualTo("project_id") assertThat(body.scores()) - .isEqualTo( - listOf( - EvalCreateParams.Score.ofFunctionId( - EvalCreateParams.Score.FunctionId.builder() - .functionId("function_id") - .build() - ) + .containsExactly( + EvalCreateParams.Score.ofFunctionId( + EvalCreateParams.Score.FunctionId.builder().functionId("function_id").build() ) ) assertThat(body.task()) diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentCreateParamsTest.kt index d7f74f35..9c672670 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentCreateParamsTest.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -75,7 +74,6 @@ internal class ExperimentCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.baseExpId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.datasetId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -115,7 +113,6 @@ internal class ExperimentCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentDeleteParamsTest.kt index cc7edd11..d3aa984d 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentDeleteParamsTest.kt @@ -15,15 +15,14 @@ internal class ExperimentDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = ExperimentDeleteParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "experimentId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentEventTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentEventTest.kt index bc31377c..44c2afc8 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentEventTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentEventTest.kt @@ -3,14 +3,17 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class ExperimentEventTest { @Test - fun createExperimentEvent() { + fun create() { val experimentEvent = ExperimentEvent.builder() .id("id") @@ -63,7 +66,7 @@ internal class ExperimentEventTest { .addSpanParent("string") .addTag("string") .build() - assertThat(experimentEvent).isNotNull + assertThat(experimentEvent.id()).isEqualTo("id") assertThat(experimentEvent._xactId()).isEqualTo("_xact_id") assertThat(experimentEvent.created()) @@ -118,7 +121,72 @@ internal class ExperimentEventTest { ) assertThat(experimentEvent.spanAttributes()) .contains(SpanAttributes.builder().name("name").type(SpanType.LLM).build()) - assertThat(experimentEvent.spanParents().get()).containsExactly("string") - assertThat(experimentEvent.tags().get()).containsExactly("string") + assertThat(experimentEvent.spanParents().getOrNull()).containsExactly("string") + assertThat(experimentEvent.tags().getOrNull()).containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val experimentEvent = + ExperimentEvent.builder() + .id("id") + ._xactId("_xact_id") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .rootSpanId("root_span_id") + .spanId("span_id") + .context( + ExperimentEvent.Context.builder() + .callerFilename("caller_filename") + .callerFunctionname("caller_functionname") + .callerLineno(0L) + .build() + ) + .error(JsonValue.from(mapOf())) + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .isRoot(true) + .metadata(ExperimentEvent.Metadata.builder().model("model").build()) + .metrics( + ExperimentEvent.Metrics.builder() + .callerFilename(JsonValue.from(mapOf())) + .callerFunctionname(JsonValue.from(mapOf())) + .callerLineno(JsonValue.from(mapOf())) + .completionTokens(0L) + .end(0.0) + .promptTokens(0L) + .start(0.0) + .tokens(0L) + .build() + ) + .origin( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + .output(JsonValue.from(mapOf())) + .scores( + ExperimentEvent.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .spanAttributes(SpanAttributes.builder().name("name").type(SpanType.LLM).build()) + .addSpanParent("string") + .addTag("string") + .build() + + val roundtrippedExperimentEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(experimentEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedExperimentEvent).isEqualTo(experimentEvent) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFeedbackParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFeedbackParamsTest.kt index 5ce9c787..ed20850d 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFeedbackParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFeedbackParamsTest.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -35,6 +34,19 @@ internal class ExperimentFeedbackParamsTest { .build() } + @Test + fun pathParams() { + val params = + ExperimentFeedbackParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addFeedback(FeedbackExperimentItem.builder().id("id").build()) + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -63,28 +75,25 @@ internal class ExperimentFeedbackParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.feedback()) - .isEqualTo( - listOf( - FeedbackExperimentItem.builder() - .id("id") - .comment("comment") - .expected(JsonValue.from(mapOf())) - .metadata( - FeedbackExperimentItem.Metadata.builder() - .putAdditionalProperty("foo", JsonValue.from("bar")) - .build() - ) - .scores( - FeedbackExperimentItem.Scores.builder() - .putAdditionalProperty("foo", JsonValue.from(0)) - .build() - ) - .source(FeedbackExperimentItem.Source.APP) - .addTag("string") - .build() - ) + .containsExactly( + FeedbackExperimentItem.builder() + .id("id") + .comment("comment") + .expected(JsonValue.from(mapOf())) + .metadata( + FeedbackExperimentItem.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .scores( + FeedbackExperimentItem.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .source(FeedbackExperimentItem.Source.APP) + .addTag("string") + .build() ) } @@ -98,22 +107,7 @@ internal class ExperimentFeedbackParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.feedback()) - .isEqualTo(listOf(FeedbackExperimentItem.builder().id("id").build())) - } - - @Test - fun getPathParam() { - val params = - ExperimentFeedbackParams.builder() - .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .addFeedback(FeedbackExperimentItem.builder().id("id").build()) - .build() - assertThat(params).isNotNull - // path param "experimentId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + .containsExactly(FeedbackExperimentItem.builder().id("id").build()) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFetchParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFetchParamsTest.kt index a4d0d229..70160fd1 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFetchParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFetchParamsTest.kt @@ -19,6 +19,18 @@ internal class ExperimentFetchParamsTest { .build() } + @Test + fun pathParams() { + val params = + ExperimentFetchParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun queryParams() { val params = @@ -54,17 +66,4 @@ internal class ExperimentFetchParamsTest { assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } - - @Test - fun getPathParam() { - val params = - ExperimentFetchParams.builder() - .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - assertThat(params).isNotNull - // path param "experimentId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFetchPostParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFetchPostParamsTest.kt index d8445769..b1a4e806 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFetchPostParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFetchPostParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -20,6 +19,18 @@ internal class ExperimentFetchPostParamsTest { .build() } + @Test + fun pathParams() { + val params = + ExperimentFetchPostParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -34,7 +45,6 @@ internal class ExperimentFetchPostParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.cursor()).contains("cursor") assertThat(body.limit()).contains(0L) assertThat(body.maxRootSpanId()).contains("max_root_span_id") @@ -50,20 +60,5 @@ internal class ExperimentFetchPostParamsTest { .build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - ExperimentFetchPostParams.builder() - .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - assertThat(params).isNotNull - // path param "experimentId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentInsertParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentInsertParamsTest.kt index aeaadaf0..105b8225 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentInsertParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentInsertParamsTest.kt @@ -4,7 +4,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue import java.time.OffsetDateTime -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -72,6 +71,19 @@ internal class ExperimentInsertParamsTest { .build() } + @Test + fun pathParams() { + val params = + ExperimentInsertParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addEvent(InsertExperimentEvent.builder().build()) + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -136,64 +148,61 @@ internal class ExperimentInsertParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.events()) - .isEqualTo( - listOf( - InsertExperimentEvent.builder() - .id("id") - ._isMerge(true) - .addMergePath(listOf("string")) - ._objectDelete(true) - ._parentId("_parent_id") - .context( - InsertExperimentEvent.Context.builder() - .callerFilename("caller_filename") - .callerFunctionname("caller_functionname") - .callerLineno(0L) - .build() - ) - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .error(JsonValue.from(mapOf())) - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata(InsertExperimentEvent.Metadata.builder().model("model").build()) - .metrics( - InsertExperimentEvent.Metrics.builder() - .callerFilename(JsonValue.from(mapOf())) - .callerFunctionname(JsonValue.from(mapOf())) - .callerLineno(JsonValue.from(mapOf())) - .completionTokens(0L) - .end(0.0) - .promptTokens(0L) - .start(0.0) - .tokens(0L) - .build() - ) - .origin( - ObjectReference.builder() - .id("id") - ._xactId("_xact_id") - .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .objectType(ObjectReference.ObjectType.EXPERIMENT) - .created("created") - .build() - ) - .output(JsonValue.from(mapOf())) - .rootSpanId("root_span_id") - .scores( - InsertExperimentEvent.Scores.builder() - .putAdditionalProperty("foo", JsonValue.from(0)) - .build() - ) - .spanAttributes( - SpanAttributes.builder().name("name").type(SpanType.LLM).build() - ) - .spanId("span_id") - .addSpanParent("string") - .addTag("string") - .build() - ) + .containsExactly( + InsertExperimentEvent.builder() + .id("id") + ._isMerge(true) + .addMergePath(listOf("string")) + ._objectDelete(true) + ._parentId("_parent_id") + .context( + InsertExperimentEvent.Context.builder() + .callerFilename("caller_filename") + .callerFunctionname("caller_functionname") + .callerLineno(0L) + .build() + ) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .error(JsonValue.from(mapOf())) + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .metadata(InsertExperimentEvent.Metadata.builder().model("model").build()) + .metrics( + InsertExperimentEvent.Metrics.builder() + .callerFilename(JsonValue.from(mapOf())) + .callerFunctionname(JsonValue.from(mapOf())) + .callerLineno(JsonValue.from(mapOf())) + .completionTokens(0L) + .end(0.0) + .promptTokens(0L) + .start(0.0) + .tokens(0L) + .build() + ) + .origin( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + .output(JsonValue.from(mapOf())) + .rootSpanId("root_span_id") + .scores( + InsertExperimentEvent.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .spanAttributes( + SpanAttributes.builder().name("name").type(SpanType.LLM).build() + ) + .spanId("span_id") + .addSpanParent("string") + .addTag("string") + .build() ) } @@ -207,21 +216,6 @@ internal class ExperimentInsertParamsTest { val body = params._body() - assertNotNull(body) - assertThat(body.events()).isEqualTo(listOf(InsertExperimentEvent.builder().build())) - } - - @Test - fun getPathParam() { - val params = - ExperimentInsertParams.builder() - .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .addEvent(InsertExperimentEvent.builder().build()) - .build() - assertThat(params).isNotNull - // path param "experimentId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(body.events()).containsExactly(InsertExperimentEvent.builder().build()) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentListPageResponseTest.kt new file mode 100644 index 00000000..867711cd --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentListPageResponseTest.kt @@ -0,0 +1,140 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ExperimentListPageResponseTest { + + @Test + fun create() { + val experimentListPageResponse = + ExperimentListPageResponse.builder() + .addObject( + Experiment.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .public_(true) + .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .commit("commit") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .datasetVersion("dataset_version") + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .metadata( + Experiment.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .repoInfo( + RepoInfo.builder() + .authorEmail("author_email") + .authorName("author_name") + .branch("branch") + .commit("commit") + .commitMessage("commit_message") + .commitTime("commit_time") + .dirty(true) + .gitDiff("git_diff") + .tag("tag") + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + assertThat(experimentListPageResponse.objects()) + .containsExactly( + Experiment.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .public_(true) + .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .commit("commit") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .datasetVersion("dataset_version") + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .metadata( + Experiment.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .repoInfo( + RepoInfo.builder() + .authorEmail("author_email") + .authorName("author_name") + .branch("branch") + .commit("commit") + .commitMessage("commit_message") + .commitTime("commit_time") + .dirty(true) + .gitDiff("git_diff") + .tag("tag") + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val experimentListPageResponse = + ExperimentListPageResponse.builder() + .addObject( + Experiment.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .public_(true) + .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .commit("commit") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .datasetVersion("dataset_version") + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .metadata( + Experiment.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .repoInfo( + RepoInfo.builder() + .authorEmail("author_email") + .authorName("author_name") + .branch("branch") + .commit("commit") + .commitMessage("commit_message") + .commitTime("commit_time") + .dirty(true) + .gitDiff("git_diff") + .tag("tag") + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + val roundtrippedExperimentListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(experimentListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedExperimentListPageResponse).isEqualTo(experimentListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentRetrieveParamsTest.kt index 435a99fd..26795ef7 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentRetrieveParamsTest.kt @@ -15,15 +15,14 @@ internal class ExperimentRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = ExperimentRetrieveParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "experimentId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentSummarizeParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentSummarizeParamsTest.kt index 3260545d..c5599fa2 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentSummarizeParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentSummarizeParamsTest.kt @@ -17,6 +17,18 @@ internal class ExperimentSummarizeParamsTest { .build() } + @Test + fun pathParams() { + val params = + ExperimentSummarizeParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun queryParams() { val params = @@ -48,17 +60,4 @@ internal class ExperimentSummarizeParamsTest { assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } - - @Test - fun getPathParam() { - val params = - ExperimentSummarizeParams.builder() - .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - assertThat(params).isNotNull - // path param "experimentId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentTest.kt index 534b2774..551f6fd0 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentTest.kt @@ -3,6 +3,8 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -10,7 +12,7 @@ import org.junit.jupiter.api.Test internal class ExperimentTest { @Test - fun createExperiment() { + fun create() { val experiment = Experiment.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -44,7 +46,7 @@ internal class ExperimentTest { ) .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(experiment).isNotNull + assertThat(experiment.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(experiment.name()).isEqualTo("name") assertThat(experiment.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -79,4 +81,50 @@ internal class ExperimentTest { ) assertThat(experiment.userId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val experiment = + Experiment.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .public_(true) + .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .commit("commit") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .datasetVersion("dataset_version") + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .metadata( + Experiment.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .repoInfo( + RepoInfo.builder() + .authorEmail("author_email") + .authorName("author_name") + .branch("branch") + .commit("commit") + .commitMessage("commit_message") + .commitTime("commit_time") + .dirty(true) + .gitDiff("git_diff") + .tag("tag") + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val roundtrippedExperiment = + jsonMapper.readValue( + jsonMapper.writeValueAsString(experiment), + jacksonTypeRef(), + ) + + assertThat(roundtrippedExperiment).isEqualTo(experiment) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentUpdateParamsTest.kt index 2284d934..214f8988 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentUpdateParamsTest.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -40,6 +39,18 @@ internal class ExperimentUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = + ExperimentUpdateParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -73,7 +84,6 @@ internal class ExperimentUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.baseExpId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.datasetId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.datasetVersion()).contains("dataset_version") @@ -110,20 +120,5 @@ internal class ExperimentUpdateParamsTest { .build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - ExperimentUpdateParams.builder() - .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - assertThat(params).isNotNull - // path param "experimentId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackDatasetItemTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackDatasetItemTest.kt index b10a7fce..4018b1b8 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackDatasetItemTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackDatasetItemTest.kt @@ -3,13 +3,16 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class FeedbackDatasetItemTest { @Test - fun createFeedbackDatasetItem() { + fun create() { val feedbackDatasetItem = FeedbackDatasetItem.builder() .id("id") @@ -22,7 +25,7 @@ internal class FeedbackDatasetItemTest { .source(FeedbackDatasetItem.Source.APP) .addTag("string") .build() - assertThat(feedbackDatasetItem).isNotNull + assertThat(feedbackDatasetItem.id()).isEqualTo("id") assertThat(feedbackDatasetItem.comment()).contains("comment") assertThat(feedbackDatasetItem.metadata()) @@ -32,6 +35,31 @@ internal class FeedbackDatasetItemTest { .build() ) assertThat(feedbackDatasetItem.source()).contains(FeedbackDatasetItem.Source.APP) - assertThat(feedbackDatasetItem.tags().get()).containsExactly("string") + assertThat(feedbackDatasetItem.tags().getOrNull()).containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val feedbackDatasetItem = + FeedbackDatasetItem.builder() + .id("id") + .comment("comment") + .metadata( + FeedbackDatasetItem.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .source(FeedbackDatasetItem.Source.APP) + .addTag("string") + .build() + + val roundtrippedFeedbackDatasetItem = + jsonMapper.readValue( + jsonMapper.writeValueAsString(feedbackDatasetItem), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFeedbackDatasetItem).isEqualTo(feedbackDatasetItem) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackExperimentItemTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackExperimentItemTest.kt index 2b36a2b7..733c7f31 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackExperimentItemTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackExperimentItemTest.kt @@ -3,13 +3,16 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class FeedbackExperimentItemTest { @Test - fun createFeedbackExperimentItem() { + fun create() { val feedbackExperimentItem = FeedbackExperimentItem.builder() .id("id") @@ -28,7 +31,7 @@ internal class FeedbackExperimentItemTest { .source(FeedbackExperimentItem.Source.APP) .addTag("string") .build() - assertThat(feedbackExperimentItem).isNotNull + assertThat(feedbackExperimentItem.id()).isEqualTo("id") assertThat(feedbackExperimentItem.comment()).contains("comment") assertThat(feedbackExperimentItem._expected()) @@ -46,6 +49,37 @@ internal class FeedbackExperimentItemTest { .build() ) assertThat(feedbackExperimentItem.source()).contains(FeedbackExperimentItem.Source.APP) - assertThat(feedbackExperimentItem.tags().get()).containsExactly("string") + assertThat(feedbackExperimentItem.tags().getOrNull()).containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val feedbackExperimentItem = + FeedbackExperimentItem.builder() + .id("id") + .comment("comment") + .expected(JsonValue.from(mapOf())) + .metadata( + FeedbackExperimentItem.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .scores( + FeedbackExperimentItem.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .source(FeedbackExperimentItem.Source.APP) + .addTag("string") + .build() + + val roundtrippedFeedbackExperimentItem = + jsonMapper.readValue( + jsonMapper.writeValueAsString(feedbackExperimentItem), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFeedbackExperimentItem).isEqualTo(feedbackExperimentItem) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackProjectLogsItemTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackProjectLogsItemTest.kt index 6fea45de..91b52fe5 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackProjectLogsItemTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackProjectLogsItemTest.kt @@ -3,13 +3,16 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class FeedbackProjectLogsItemTest { @Test - fun createFeedbackProjectLogsItem() { + fun create() { val feedbackProjectLogsItem = FeedbackProjectLogsItem.builder() .id("id") @@ -28,7 +31,7 @@ internal class FeedbackProjectLogsItemTest { .source(FeedbackProjectLogsItem.Source.APP) .addTag("string") .build() - assertThat(feedbackProjectLogsItem).isNotNull + assertThat(feedbackProjectLogsItem.id()).isEqualTo("id") assertThat(feedbackProjectLogsItem.comment()).contains("comment") assertThat(feedbackProjectLogsItem._expected()) @@ -46,6 +49,37 @@ internal class FeedbackProjectLogsItemTest { .build() ) assertThat(feedbackProjectLogsItem.source()).contains(FeedbackProjectLogsItem.Source.APP) - assertThat(feedbackProjectLogsItem.tags().get()).containsExactly("string") + assertThat(feedbackProjectLogsItem.tags().getOrNull()).containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val feedbackProjectLogsItem = + FeedbackProjectLogsItem.builder() + .id("id") + .comment("comment") + .expected(JsonValue.from(mapOf())) + .metadata( + FeedbackProjectLogsItem.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .scores( + FeedbackProjectLogsItem.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .source(FeedbackProjectLogsItem.Source.APP) + .addTag("string") + .build() + + val roundtrippedFeedbackProjectLogsItem = + jsonMapper.readValue( + jsonMapper.writeValueAsString(feedbackProjectLogsItem), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFeedbackProjectLogsItem).isEqualTo(feedbackProjectLogsItem) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackResponseSchemaTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackResponseSchemaTest.kt index bafdb30c..f7e73e95 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackResponseSchemaTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackResponseSchemaTest.kt @@ -2,16 +2,33 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class FeedbackResponseSchemaTest { @Test - fun createFeedbackResponseSchema() { + fun create() { val feedbackResponseSchema = FeedbackResponseSchema.builder().status(FeedbackResponseSchema.Status.SUCCESS).build() - assertThat(feedbackResponseSchema).isNotNull + assertThat(feedbackResponseSchema.status()).isEqualTo(FeedbackResponseSchema.Status.SUCCESS) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val feedbackResponseSchema = + FeedbackResponseSchema.builder().status(FeedbackResponseSchema.Status.SUCCESS).build() + + val roundtrippedFeedbackResponseSchema = + jsonMapper.readValue( + jsonMapper.writeValueAsString(feedbackResponseSchema), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFeedbackResponseSchema).isEqualTo(feedbackResponseSchema) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FetchDatasetEventsResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FetchDatasetEventsResponseTest.kt index ced9effd..b61492e2 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FetchDatasetEventsResponseTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FetchDatasetEventsResponseTest.kt @@ -3,6 +3,8 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -10,7 +12,7 @@ import org.junit.jupiter.api.Test internal class FetchDatasetEventsResponseTest { @Test - fun createFetchDatasetEventsResponse() { + fun create() { val fetchDatasetEventsResponse = FetchDatasetEventsResponse.builder() .addEvent( @@ -40,7 +42,7 @@ internal class FetchDatasetEventsResponseTest { ) .cursor("cursor") .build() - assertThat(fetchDatasetEventsResponse).isNotNull + assertThat(fetchDatasetEventsResponse.events()) .containsExactly( DatasetEvent.builder() @@ -69,4 +71,46 @@ internal class FetchDatasetEventsResponseTest { ) assertThat(fetchDatasetEventsResponse.cursor()).contains("cursor") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val fetchDatasetEventsResponse = + FetchDatasetEventsResponse.builder() + .addEvent( + DatasetEvent.builder() + .id("id") + ._xactId("_xact_id") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .rootSpanId("root_span_id") + .spanId("span_id") + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .isRoot(true) + .metadata(DatasetEvent.Metadata.builder().model("model").build()) + .origin( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + .addTag("string") + .build() + ) + .cursor("cursor") + .build() + + val roundtrippedFetchDatasetEventsResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(fetchDatasetEventsResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFetchDatasetEventsResponse).isEqualTo(fetchDatasetEventsResponse) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FetchExperimentEventsResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FetchExperimentEventsResponseTest.kt index 7ec8e63b..89e2327e 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FetchExperimentEventsResponseTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FetchExperimentEventsResponseTest.kt @@ -3,6 +3,8 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -10,7 +12,7 @@ import org.junit.jupiter.api.Test internal class FetchExperimentEventsResponseTest { @Test - fun createFetchExperimentEventsResponse() { + fun create() { val fetchExperimentEventsResponse = FetchExperimentEventsResponse.builder() .addEvent( @@ -70,7 +72,7 @@ internal class FetchExperimentEventsResponseTest { ) .cursor("cursor") .build() - assertThat(fetchExperimentEventsResponse).isNotNull + assertThat(fetchExperimentEventsResponse.events()) .containsExactly( ExperimentEvent.builder() @@ -129,4 +131,77 @@ internal class FetchExperimentEventsResponseTest { ) assertThat(fetchExperimentEventsResponse.cursor()).contains("cursor") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val fetchExperimentEventsResponse = + FetchExperimentEventsResponse.builder() + .addEvent( + ExperimentEvent.builder() + .id("id") + ._xactId("_xact_id") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .rootSpanId("root_span_id") + .spanId("span_id") + .context( + ExperimentEvent.Context.builder() + .callerFilename("caller_filename") + .callerFunctionname("caller_functionname") + .callerLineno(0L) + .build() + ) + .error(JsonValue.from(mapOf())) + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .isRoot(true) + .metadata(ExperimentEvent.Metadata.builder().model("model").build()) + .metrics( + ExperimentEvent.Metrics.builder() + .callerFilename(JsonValue.from(mapOf())) + .callerFunctionname(JsonValue.from(mapOf())) + .callerLineno(JsonValue.from(mapOf())) + .completionTokens(0L) + .end(0.0) + .promptTokens(0L) + .start(0.0) + .tokens(0L) + .build() + ) + .origin( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + .output(JsonValue.from(mapOf())) + .scores( + ExperimentEvent.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .spanAttributes( + SpanAttributes.builder().name("name").type(SpanType.LLM).build() + ) + .addSpanParent("string") + .addTag("string") + .build() + ) + .cursor("cursor") + .build() + + val roundtrippedFetchExperimentEventsResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(fetchExperimentEventsResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFetchExperimentEventsResponse) + .isEqualTo(fetchExperimentEventsResponse) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FetchProjectLogsEventsResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FetchProjectLogsEventsResponseTest.kt index ae7b0b5a..53d51aa5 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FetchProjectLogsEventsResponseTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FetchProjectLogsEventsResponseTest.kt @@ -3,6 +3,8 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -10,7 +12,7 @@ import org.junit.jupiter.api.Test internal class FetchProjectLogsEventsResponseTest { @Test - fun createFetchProjectLogsEventsResponse() { + fun create() { val fetchProjectLogsEventsResponse = FetchProjectLogsEventsResponse.builder() .addEvent( @@ -71,7 +73,7 @@ internal class FetchProjectLogsEventsResponseTest { ) .cursor("cursor") .build() - assertThat(fetchProjectLogsEventsResponse).isNotNull + assertThat(fetchProjectLogsEventsResponse.events()) .containsExactly( ProjectLogsEvent.builder() @@ -131,4 +133,78 @@ internal class FetchProjectLogsEventsResponseTest { ) assertThat(fetchProjectLogsEventsResponse.cursor()).contains("cursor") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val fetchProjectLogsEventsResponse = + FetchProjectLogsEventsResponse.builder() + .addEvent( + ProjectLogsEvent.builder() + .id("id") + ._xactId("_xact_id") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .logId(ProjectLogsEvent.LogId.G) + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .rootSpanId("root_span_id") + .spanId("span_id") + .context( + ProjectLogsEvent.Context.builder() + .callerFilename("caller_filename") + .callerFunctionname("caller_functionname") + .callerLineno(0L) + .build() + ) + .error(JsonValue.from(mapOf())) + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .isRoot(true) + .metadata(ProjectLogsEvent.Metadata.builder().model("model").build()) + .metrics( + ProjectLogsEvent.Metrics.builder() + .callerFilename(JsonValue.from(mapOf())) + .callerFunctionname(JsonValue.from(mapOf())) + .callerLineno(JsonValue.from(mapOf())) + .completionTokens(0L) + .end(0.0) + .promptTokens(0L) + .start(0.0) + .tokens(0L) + .build() + ) + .origin( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + .output(JsonValue.from(mapOf())) + .scores( + ProjectLogsEvent.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .spanAttributes( + SpanAttributes.builder().name("name").type(SpanType.LLM).build() + ) + .addSpanParent("string") + .addTag("string") + .build() + ) + .cursor("cursor") + .build() + + val roundtrippedFetchProjectLogsEventsResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(fetchProjectLogsEventsResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFetchProjectLogsEventsResponse) + .isEqualTo(fetchProjectLogsEventsResponse) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionCreateParamsTest.kt index a4747bcf..1c191402 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionCreateParamsTest.kt @@ -3,7 +3,7 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -230,7 +230,6 @@ internal class FunctionCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.functionData()) .isEqualTo( FunctionCreateParams.FunctionData.ofPrompt( @@ -339,7 +338,7 @@ internal class FunctionCreateParamsTest { ) .build() ) - assertThat(body.tags()).contains(listOf("string")) + assertThat(body.tags().getOrNull()).containsExactly("string") } @Test @@ -358,7 +357,6 @@ internal class FunctionCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.functionData()) .isEqualTo( FunctionCreateParams.FunctionData.ofPrompt( diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionDeleteParamsTest.kt index 4b8a7c19..3e0df519 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionDeleteParamsTest.kt @@ -13,15 +13,14 @@ internal class FunctionDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = FunctionDeleteParams.builder() .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "functionId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionInvokeParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionInvokeParamsTest.kt index 988dc6e4..5709c972 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionInvokeParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionInvokeParamsTest.kt @@ -3,7 +3,7 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -53,6 +53,18 @@ internal class FunctionInvokeParamsTest { .build() } + @Test + fun pathParams() { + val params = + FunctionInvokeParams.builder() + .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -99,19 +111,16 @@ internal class FunctionInvokeParamsTest { val body = params._body() - assertNotNull(body) assertThat(body._expected()).isEqualTo(JsonValue.from(mapOf())) assertThat(body._input()).isEqualTo(JsonValue.from(mapOf())) - assertThat(body.messages()) - .contains( - listOf( - FunctionInvokeParams.Message.ofSystem( - FunctionInvokeParams.Message.System.builder() - .role(FunctionInvokeParams.Message.System.Role.SYSTEM) - .content("content") - .name("name") - .build() - ) + assertThat(body.messages().getOrNull()) + .containsExactly( + FunctionInvokeParams.Message.ofSystem( + FunctionInvokeParams.Message.System.builder() + .role(FunctionInvokeParams.Message.System.Role.SYSTEM) + .content("content") + .name("name") + .build() ) ) assertThat(body.metadata()) @@ -156,20 +165,5 @@ internal class FunctionInvokeParamsTest { .build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - FunctionInvokeParams.builder() - .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - assertThat(params).isNotNull - // path param "functionId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionInvokeResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionInvokeResponseTest.kt new file mode 100644 index 00000000..e1467ea3 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionInvokeResponseTest.kt @@ -0,0 +1,30 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FunctionInvokeResponseTest { + + @Test + fun create() { + val functionInvokeResponse = FunctionInvokeResponse.builder().build() + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val functionInvokeResponse = FunctionInvokeResponse.builder().build() + + val roundtrippedFunctionInvokeResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(functionInvokeResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFunctionInvokeResponse).isEqualTo(functionInvokeResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionListPageResponseTest.kt new file mode 100644 index 00000000..f4021ef8 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionListPageResponseTest.kt @@ -0,0 +1,402 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FunctionListPageResponseTest { + + @Test + fun create() { + val functionListPageResponse = + FunctionListPageResponse.builder() + .addObject( + Function.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + ._xactId("_xact_id") + .functionData( + Function.FunctionData.Prompt.builder() + .type(Function.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .logId(Function.LogId.P) + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("slug") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .functionSchema( + Function.FunctionSchema.builder() + .parameters(JsonValue.from(mapOf())) + .returns(JsonValue.from(mapOf())) + .build() + ) + .functionType(Function.FunctionType.LLM) + .metadata( + Function.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .origin( + Function.Origin.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .internal_(true) + .build() + ) + .promptData( + PromptData.builder() + .options( + PromptOptions.builder() + .model("model") + .params( + PromptOptions.Params.OpenAIModelParams.builder() + .frequencyPenalty(0.0) + .functionCall( + PromptOptions.Params.OpenAIModelParams + .FunctionCall + .UnionMember0 + .AUTO + ) + .maxCompletionTokens(0.0) + .maxTokens(0.0) + .n(0.0) + .presencePenalty(0.0) + .reasoningEffort( + PromptOptions.Params.OpenAIModelParams + .ReasoningEffort + .LOW + ) + .responseFormat( + PromptOptions.Params.OpenAIModelParams + .ResponseFormat + .JsonObject + .builder() + .type( + PromptOptions.Params.OpenAIModelParams + .ResponseFormat + .JsonObject + .Type + .JSON_OBJECT + ) + .build() + ) + .addStop("string") + .temperature(0.0) + .toolChoice( + PromptOptions.Params.OpenAIModelParams + .ToolChoice + .UnionMember0 + .AUTO + ) + .topP(0.0) + .useCache(true) + .build() + ) + .position("position") + .build() + ) + .origin( + PromptData.Origin.builder() + .projectId("project_id") + .promptId("prompt_id") + .promptVersion("prompt_version") + .build() + ) + .parser( + PromptData.Parser.builder() + .choiceScores( + PromptData.Parser.ChoiceScores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .type(PromptData.Parser.Type.LLM_CLASSIFIER) + .useCot(true) + .build() + ) + .prompt( + PromptData.Prompt.Completion.builder() + .content("content") + .type(PromptData.Prompt.Completion.Type.COMPLETION) + .build() + ) + .addToolFunction( + PromptData.ToolFunction.Function.builder() + .id("id") + .type(PromptData.ToolFunction.Function.Type.FUNCTION) + .build() + ) + .build() + ) + .addTag("string") + .build() + ) + .build() + + assertThat(functionListPageResponse.objects()) + .containsExactly( + Function.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + ._xactId("_xact_id") + .functionData( + Function.FunctionData.Prompt.builder() + .type(Function.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .logId(Function.LogId.P) + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("slug") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .functionSchema( + Function.FunctionSchema.builder() + .parameters(JsonValue.from(mapOf())) + .returns(JsonValue.from(mapOf())) + .build() + ) + .functionType(Function.FunctionType.LLM) + .metadata( + Function.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .origin( + Function.Origin.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .internal_(true) + .build() + ) + .promptData( + PromptData.builder() + .options( + PromptOptions.builder() + .model("model") + .params( + PromptOptions.Params.OpenAIModelParams.builder() + .frequencyPenalty(0.0) + .functionCall( + PromptOptions.Params.OpenAIModelParams.FunctionCall + .UnionMember0 + .AUTO + ) + .maxCompletionTokens(0.0) + .maxTokens(0.0) + .n(0.0) + .presencePenalty(0.0) + .reasoningEffort( + PromptOptions.Params.OpenAIModelParams + .ReasoningEffort + .LOW + ) + .responseFormat( + PromptOptions.Params.OpenAIModelParams + .ResponseFormat + .JsonObject + .builder() + .type( + PromptOptions.Params.OpenAIModelParams + .ResponseFormat + .JsonObject + .Type + .JSON_OBJECT + ) + .build() + ) + .addStop("string") + .temperature(0.0) + .toolChoice( + PromptOptions.Params.OpenAIModelParams.ToolChoice + .UnionMember0 + .AUTO + ) + .topP(0.0) + .useCache(true) + .build() + ) + .position("position") + .build() + ) + .origin( + PromptData.Origin.builder() + .projectId("project_id") + .promptId("prompt_id") + .promptVersion("prompt_version") + .build() + ) + .parser( + PromptData.Parser.builder() + .choiceScores( + PromptData.Parser.ChoiceScores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .type(PromptData.Parser.Type.LLM_CLASSIFIER) + .useCot(true) + .build() + ) + .prompt( + PromptData.Prompt.Completion.builder() + .content("content") + .type(PromptData.Prompt.Completion.Type.COMPLETION) + .build() + ) + .addToolFunction( + PromptData.ToolFunction.Function.builder() + .id("id") + .type(PromptData.ToolFunction.Function.Type.FUNCTION) + .build() + ) + .build() + ) + .addTag("string") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val functionListPageResponse = + FunctionListPageResponse.builder() + .addObject( + Function.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + ._xactId("_xact_id") + .functionData( + Function.FunctionData.Prompt.builder() + .type(Function.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .logId(Function.LogId.P) + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("slug") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .functionSchema( + Function.FunctionSchema.builder() + .parameters(JsonValue.from(mapOf())) + .returns(JsonValue.from(mapOf())) + .build() + ) + .functionType(Function.FunctionType.LLM) + .metadata( + Function.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .origin( + Function.Origin.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .internal_(true) + .build() + ) + .promptData( + PromptData.builder() + .options( + PromptOptions.builder() + .model("model") + .params( + PromptOptions.Params.OpenAIModelParams.builder() + .frequencyPenalty(0.0) + .functionCall( + PromptOptions.Params.OpenAIModelParams + .FunctionCall + .UnionMember0 + .AUTO + ) + .maxCompletionTokens(0.0) + .maxTokens(0.0) + .n(0.0) + .presencePenalty(0.0) + .reasoningEffort( + PromptOptions.Params.OpenAIModelParams + .ReasoningEffort + .LOW + ) + .responseFormat( + PromptOptions.Params.OpenAIModelParams + .ResponseFormat + .JsonObject + .builder() + .type( + PromptOptions.Params.OpenAIModelParams + .ResponseFormat + .JsonObject + .Type + .JSON_OBJECT + ) + .build() + ) + .addStop("string") + .temperature(0.0) + .toolChoice( + PromptOptions.Params.OpenAIModelParams + .ToolChoice + .UnionMember0 + .AUTO + ) + .topP(0.0) + .useCache(true) + .build() + ) + .position("position") + .build() + ) + .origin( + PromptData.Origin.builder() + .projectId("project_id") + .promptId("prompt_id") + .promptVersion("prompt_version") + .build() + ) + .parser( + PromptData.Parser.builder() + .choiceScores( + PromptData.Parser.ChoiceScores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .type(PromptData.Parser.Type.LLM_CLASSIFIER) + .useCot(true) + .build() + ) + .prompt( + PromptData.Prompt.Completion.builder() + .content("content") + .type(PromptData.Prompt.Completion.Type.COMPLETION) + .build() + ) + .addToolFunction( + PromptData.ToolFunction.Function.builder() + .id("id") + .type(PromptData.ToolFunction.Function.Type.FUNCTION) + .build() + ) + .build() + ) + .addTag("string") + .build() + ) + .build() + + val roundtrippedFunctionListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(functionListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFunctionListPageResponse).isEqualTo(functionListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionReplaceParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionReplaceParamsTest.kt index a1c6af81..3e43d5eb 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionReplaceParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionReplaceParamsTest.kt @@ -3,7 +3,7 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -230,7 +230,6 @@ internal class FunctionReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.functionData()) .isEqualTo( FunctionReplaceParams.FunctionData.ofPrompt( @@ -339,7 +338,7 @@ internal class FunctionReplaceParamsTest { ) .build() ) - assertThat(body.tags()).contains(listOf("string")) + assertThat(body.tags().getOrNull()).containsExactly("string") } @Test @@ -358,7 +357,6 @@ internal class FunctionReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.functionData()) .isEqualTo( FunctionReplaceParams.FunctionData.ofPrompt( diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionRetrieveParamsTest.kt index 9890c9f3..fd70fae8 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionRetrieveParamsTest.kt @@ -13,15 +13,14 @@ internal class FunctionRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = FunctionRetrieveParams.builder() .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "functionId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionTest.kt index b42ee0e0..45ecb9f8 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionTest.kt @@ -3,14 +3,17 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class FunctionTest { @Test - fun createFunction() { + fun create() { val function = Function.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -128,7 +131,7 @@ internal class FunctionTest { ) .addTag("string") .build() - assertThat(function).isNotNull + assertThat(function.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(function._xactId()).isEqualTo("_xact_id") assertThat(function.functionData()) @@ -248,6 +251,136 @@ internal class FunctionTest { ) .build() ) - assertThat(function.tags().get()).containsExactly("string") + assertThat(function.tags().getOrNull()).containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val function = + Function.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + ._xactId("_xact_id") + .functionData( + Function.FunctionData.Prompt.builder() + .type(Function.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .logId(Function.LogId.P) + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("slug") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .functionSchema( + Function.FunctionSchema.builder() + .parameters(JsonValue.from(mapOf())) + .returns(JsonValue.from(mapOf())) + .build() + ) + .functionType(Function.FunctionType.LLM) + .metadata( + Function.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .origin( + Function.Origin.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .internal_(true) + .build() + ) + .promptData( + PromptData.builder() + .options( + PromptOptions.builder() + .model("model") + .params( + PromptOptions.Params.OpenAIModelParams.builder() + .frequencyPenalty(0.0) + .functionCall( + PromptOptions.Params.OpenAIModelParams.FunctionCall + .UnionMember0 + .AUTO + ) + .maxCompletionTokens(0.0) + .maxTokens(0.0) + .n(0.0) + .presencePenalty(0.0) + .reasoningEffort( + PromptOptions.Params.OpenAIModelParams.ReasoningEffort + .LOW + ) + .responseFormat( + PromptOptions.Params.OpenAIModelParams.ResponseFormat + .JsonObject + .builder() + .type( + PromptOptions.Params.OpenAIModelParams + .ResponseFormat + .JsonObject + .Type + .JSON_OBJECT + ) + .build() + ) + .addStop("string") + .temperature(0.0) + .toolChoice( + PromptOptions.Params.OpenAIModelParams.ToolChoice + .UnionMember0 + .AUTO + ) + .topP(0.0) + .useCache(true) + .build() + ) + .position("position") + .build() + ) + .origin( + PromptData.Origin.builder() + .projectId("project_id") + .promptId("prompt_id") + .promptVersion("prompt_version") + .build() + ) + .parser( + PromptData.Parser.builder() + .choiceScores( + PromptData.Parser.ChoiceScores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .type(PromptData.Parser.Type.LLM_CLASSIFIER) + .useCot(true) + .build() + ) + .prompt( + PromptData.Prompt.Completion.builder() + .content("content") + .type(PromptData.Prompt.Completion.Type.COMPLETION) + .build() + ) + .addToolFunction( + PromptData.ToolFunction.Function.builder() + .id("id") + .type(PromptData.ToolFunction.Function.Type.FUNCTION) + .build() + ) + .build() + ) + .addTag("string") + .build() + + val roundtrippedFunction = + jsonMapper.readValue( + jsonMapper.writeValueAsString(function), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFunction).isEqualTo(function) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionUpdateParamsTest.kt index 261982cd..efa128b9 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionUpdateParamsTest.kt @@ -3,7 +3,7 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -103,6 +103,18 @@ internal class FunctionUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = + FunctionUpdateParams.builder() + .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -200,7 +212,6 @@ internal class FunctionUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.description()).contains("description") assertThat(body.functionData()) .contains( @@ -291,7 +302,7 @@ internal class FunctionUpdateParamsTest { ) .build() ) - assertThat(body.tags()).contains(listOf("string")) + assertThat(body.tags().getOrNull()).containsExactly("string") } @Test @@ -302,20 +313,5 @@ internal class FunctionUpdateParamsTest { .build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - FunctionUpdateParams.builder() - .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - assertThat(params).isNotNull - // path param "functionId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupCreateParamsTest.kt index 4707e762..f050afce 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupCreateParamsTest.kt @@ -2,7 +2,7 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -32,11 +32,12 @@ internal class GroupCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") assertThat(body.description()).contains("description") - assertThat(body.memberGroups()).contains(listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) - assertThat(body.memberUsers()).contains(listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) + assertThat(body.memberGroups().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.memberUsers().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.orgName()).contains("org_name") } @@ -46,7 +47,6 @@ internal class GroupCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupDeleteParamsTest.kt index 362fe3f6..3f194aea 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupDeleteParamsTest.kt @@ -13,13 +13,12 @@ internal class GroupDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = GroupDeleteParams.builder().groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "groupId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupListPageResponseTest.kt new file mode 100644 index 00000000..136b59ee --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupListPageResponseTest.kt @@ -0,0 +1,76 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class GroupListPageResponseTest { + + @Test + fun create() { + val groupListPageResponse = + GroupListPageResponse.builder() + .addObject( + Group.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .addMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + assertThat(groupListPageResponse.objects()) + .containsExactly( + Group.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .addMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val groupListPageResponse = + GroupListPageResponse.builder() + .addObject( + Group.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .addMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + val roundtrippedGroupListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(groupListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedGroupListPageResponse).isEqualTo(groupListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupReplaceParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupReplaceParamsTest.kt index d5c3f0ec..380f91aa 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupReplaceParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupReplaceParamsTest.kt @@ -2,7 +2,7 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -32,11 +32,12 @@ internal class GroupReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") assertThat(body.description()).contains("description") - assertThat(body.memberGroups()).contains(listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) - assertThat(body.memberUsers()).contains(listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) + assertThat(body.memberGroups().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.memberUsers().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.orgName()).contains("org_name") } @@ -46,7 +47,6 @@ internal class GroupReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupRetrieveParamsTest.kt index ea355d6a..88125d11 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupRetrieveParamsTest.kt @@ -13,13 +13,12 @@ internal class GroupRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = GroupRetrieveParams.builder().groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "groupId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupTest.kt index 235fb2a1..1f75b26f 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupTest.kt @@ -2,14 +2,17 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class GroupTest { @Test - fun createGroup() { + fun create() { val group = Group.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -22,17 +25,39 @@ internal class GroupTest { .addMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(group).isNotNull + assertThat(group.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(group.name()).isEqualTo("name") assertThat(group.orgId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(group.created()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) assertThat(group.deletedAt()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) assertThat(group.description()).contains("description") - assertThat(group.memberGroups().get()) + assertThat(group.memberGroups().getOrNull()) .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(group.memberUsers().get()) + assertThat(group.memberUsers().getOrNull()) .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(group.userId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val group = + Group.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .addMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val roundtrippedGroup = + jsonMapper.readValue(jsonMapper.writeValueAsString(group), jacksonTypeRef()) + + assertThat(roundtrippedGroup).isEqualTo(group) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupUpdateParamsTest.kt index ece1b27d..f5ea0ee6 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupUpdateParamsTest.kt @@ -2,7 +2,7 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -21,6 +21,16 @@ internal class GroupUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = + GroupUpdateParams.builder().groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -36,15 +46,16 @@ internal class GroupUpdateParamsTest { val body = params._body() - assertNotNull(body) - assertThat(body.addMemberGroups()).contains(listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) - assertThat(body.addMemberUsers()).contains(listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) + assertThat(body.addMemberGroups().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.addMemberUsers().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.description()).contains("description") assertThat(body.name()).contains("x") - assertThat(body.removeMemberGroups()) - .contains(listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) - assertThat(body.removeMemberUsers()) - .contains(listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) + assertThat(body.removeMemberGroups().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.removeMemberUsers().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } @Test @@ -53,18 +64,5 @@ internal class GroupUpdateParamsTest { GroupUpdateParams.builder().groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - GroupUpdateParams.builder().groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "groupId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertDatasetEventTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertDatasetEventTest.kt index 176a9e81..77302d95 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertDatasetEventTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertDatasetEventTest.kt @@ -3,14 +3,17 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class InsertDatasetEventTest { @Test - fun createInsertDatasetEvent() { + fun create() { val insertDatasetEvent = InsertDatasetEvent.builder() .id("id") @@ -36,10 +39,10 @@ internal class InsertDatasetEventTest { .addSpanParent("string") .addTag("string") .build() - assertThat(insertDatasetEvent).isNotNull + assertThat(insertDatasetEvent.id()).contains("id") assertThat(insertDatasetEvent._isMerge()).contains(true) - assertThat(insertDatasetEvent._mergePaths().get()).containsExactly(listOf("string")) + assertThat(insertDatasetEvent._mergePaths().getOrNull()).containsExactly(listOf("string")) assertThat(insertDatasetEvent._objectDelete()).contains(true) assertThat(insertDatasetEvent._parentId()).contains("_parent_id") assertThat(insertDatasetEvent.created()) @@ -60,7 +63,45 @@ internal class InsertDatasetEventTest { ) assertThat(insertDatasetEvent.rootSpanId()).contains("root_span_id") assertThat(insertDatasetEvent.spanId()).contains("span_id") - assertThat(insertDatasetEvent.spanParents().get()).containsExactly("string") - assertThat(insertDatasetEvent.tags().get()).containsExactly("string") + assertThat(insertDatasetEvent.spanParents().getOrNull()).containsExactly("string") + assertThat(insertDatasetEvent.tags().getOrNull()).containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val insertDatasetEvent = + InsertDatasetEvent.builder() + .id("id") + ._isMerge(true) + .addMergePath(listOf("string")) + ._objectDelete(true) + ._parentId("_parent_id") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .metadata(InsertDatasetEvent.Metadata.builder().model("model").build()) + .origin( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + .rootSpanId("root_span_id") + .spanId("span_id") + .addSpanParent("string") + .addTag("string") + .build() + + val roundtrippedInsertDatasetEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(insertDatasetEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedInsertDatasetEvent).isEqualTo(insertDatasetEvent) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertEventsResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertEventsResponseTest.kt index bc8f0a96..560e7fd1 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertEventsResponseTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertEventsResponseTest.kt @@ -2,15 +2,31 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class InsertEventsResponseTest { @Test - fun createInsertEventsResponse() { + fun create() { val insertEventsResponse = InsertEventsResponse.builder().addRowId("string").build() - assertThat(insertEventsResponse).isNotNull + assertThat(insertEventsResponse.rowIds()).containsExactly("string") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val insertEventsResponse = InsertEventsResponse.builder().addRowId("string").build() + + val roundtrippedInsertEventsResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(insertEventsResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedInsertEventsResponse).isEqualTo(insertEventsResponse) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertExperimentEventTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertExperimentEventTest.kt index 3f52dc7f..c56170f1 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertExperimentEventTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertExperimentEventTest.kt @@ -3,14 +3,17 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class InsertExperimentEventTest { @Test - fun createInsertExperimentEvent() { + fun create() { val insertExperimentEvent = InsertExperimentEvent.builder() .id("id") @@ -63,10 +66,11 @@ internal class InsertExperimentEventTest { .addSpanParent("string") .addTag("string") .build() - assertThat(insertExperimentEvent).isNotNull + assertThat(insertExperimentEvent.id()).contains("id") assertThat(insertExperimentEvent._isMerge()).contains(true) - assertThat(insertExperimentEvent._mergePaths().get()).containsExactly(listOf("string")) + assertThat(insertExperimentEvent._mergePaths().getOrNull()) + .containsExactly(listOf("string")) assertThat(insertExperimentEvent._objectDelete()).contains(true) assertThat(insertExperimentEvent._parentId()).contains("_parent_id") assertThat(insertExperimentEvent.context()) @@ -119,7 +123,72 @@ internal class InsertExperimentEventTest { assertThat(insertExperimentEvent.spanAttributes()) .contains(SpanAttributes.builder().name("name").type(SpanType.LLM).build()) assertThat(insertExperimentEvent.spanId()).contains("span_id") - assertThat(insertExperimentEvent.spanParents().get()).containsExactly("string") - assertThat(insertExperimentEvent.tags().get()).containsExactly("string") + assertThat(insertExperimentEvent.spanParents().getOrNull()).containsExactly("string") + assertThat(insertExperimentEvent.tags().getOrNull()).containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val insertExperimentEvent = + InsertExperimentEvent.builder() + .id("id") + ._isMerge(true) + .addMergePath(listOf("string")) + ._objectDelete(true) + ._parentId("_parent_id") + .context( + InsertExperimentEvent.Context.builder() + .callerFilename("caller_filename") + .callerFunctionname("caller_functionname") + .callerLineno(0L) + .build() + ) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .error(JsonValue.from(mapOf())) + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .metadata(InsertExperimentEvent.Metadata.builder().model("model").build()) + .metrics( + InsertExperimentEvent.Metrics.builder() + .callerFilename(JsonValue.from(mapOf())) + .callerFunctionname(JsonValue.from(mapOf())) + .callerLineno(JsonValue.from(mapOf())) + .completionTokens(0L) + .end(0.0) + .promptTokens(0L) + .start(0.0) + .tokens(0L) + .build() + ) + .origin( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + .output(JsonValue.from(mapOf())) + .rootSpanId("root_span_id") + .scores( + InsertExperimentEvent.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .spanAttributes(SpanAttributes.builder().name("name").type(SpanType.LLM).build()) + .spanId("span_id") + .addSpanParent("string") + .addTag("string") + .build() + + val roundtrippedInsertExperimentEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(insertExperimentEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedInsertExperimentEvent).isEqualTo(insertExperimentEvent) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertProjectLogsEventTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertProjectLogsEventTest.kt index b3812878..5320624c 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertProjectLogsEventTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertProjectLogsEventTest.kt @@ -3,14 +3,17 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class InsertProjectLogsEventTest { @Test - fun createInsertProjectLogsEvent() { + fun create() { val insertProjectLogsEvent = InsertProjectLogsEvent.builder() .id("id") @@ -63,10 +66,11 @@ internal class InsertProjectLogsEventTest { .addSpanParent("string") .addTag("string") .build() - assertThat(insertProjectLogsEvent).isNotNull + assertThat(insertProjectLogsEvent.id()).contains("id") assertThat(insertProjectLogsEvent._isMerge()).contains(true) - assertThat(insertProjectLogsEvent._mergePaths().get()).containsExactly(listOf("string")) + assertThat(insertProjectLogsEvent._mergePaths().getOrNull()) + .containsExactly(listOf("string")) assertThat(insertProjectLogsEvent._objectDelete()).contains(true) assertThat(insertProjectLogsEvent._parentId()).contains("_parent_id") assertThat(insertProjectLogsEvent.context()) @@ -119,7 +123,72 @@ internal class InsertProjectLogsEventTest { assertThat(insertProjectLogsEvent.spanAttributes()) .contains(SpanAttributes.builder().name("name").type(SpanType.LLM).build()) assertThat(insertProjectLogsEvent.spanId()).contains("span_id") - assertThat(insertProjectLogsEvent.spanParents().get()).containsExactly("string") - assertThat(insertProjectLogsEvent.tags().get()).containsExactly("string") + assertThat(insertProjectLogsEvent.spanParents().getOrNull()).containsExactly("string") + assertThat(insertProjectLogsEvent.tags().getOrNull()).containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val insertProjectLogsEvent = + InsertProjectLogsEvent.builder() + .id("id") + ._isMerge(true) + .addMergePath(listOf("string")) + ._objectDelete(true) + ._parentId("_parent_id") + .context( + InsertProjectLogsEvent.Context.builder() + .callerFilename("caller_filename") + .callerFunctionname("caller_functionname") + .callerLineno(0L) + .build() + ) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .error(JsonValue.from(mapOf())) + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .metadata(InsertProjectLogsEvent.Metadata.builder().model("model").build()) + .metrics( + InsertProjectLogsEvent.Metrics.builder() + .callerFilename(JsonValue.from(mapOf())) + .callerFunctionname(JsonValue.from(mapOf())) + .callerLineno(JsonValue.from(mapOf())) + .completionTokens(0L) + .end(0.0) + .promptTokens(0L) + .start(0.0) + .tokens(0L) + .build() + ) + .origin( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + .output(JsonValue.from(mapOf())) + .rootSpanId("root_span_id") + .scores( + InsertProjectLogsEvent.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .spanAttributes(SpanAttributes.builder().name("name").type(SpanType.LLM).build()) + .spanId("span_id") + .addSpanParent("string") + .addTag("string") + .build() + + val roundtrippedInsertProjectLogsEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(insertProjectLogsEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedInsertProjectLogsEvent).isEqualTo(insertProjectLogsEvent) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/MetricSummaryTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/MetricSummaryTest.kt index a1dc0294..e236bd38 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/MetricSummaryTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/MetricSummaryTest.kt @@ -2,13 +2,15 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class MetricSummaryTest { @Test - fun createMetricSummary() { + fun create() { val metricSummary = MetricSummary.builder() .improvements(0L) @@ -18,7 +20,7 @@ internal class MetricSummaryTest { .unit("unit") .diff(0.0) .build() - assertThat(metricSummary).isNotNull + assertThat(metricSummary.improvements()).isEqualTo(0L) assertThat(metricSummary.metric()).isEqualTo(0.0) assertThat(metricSummary.name()).isEqualTo("name") @@ -26,4 +28,26 @@ internal class MetricSummaryTest { assertThat(metricSummary.unit()).isEqualTo("unit") assertThat(metricSummary.diff()).contains(0.0) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val metricSummary = + MetricSummary.builder() + .improvements(0L) + .metric(0.0) + .name("name") + .regressions(0L) + .unit("unit") + .diff(0.0) + .build() + + val roundtrippedMetricSummary = + jsonMapper.readValue( + jsonMapper.writeValueAsString(metricSummary), + jacksonTypeRef(), + ) + + assertThat(roundtrippedMetricSummary).isEqualTo(metricSummary) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ObjectReferenceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ObjectReferenceTest.kt index cd116d19..80d4a6e0 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ObjectReferenceTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ObjectReferenceTest.kt @@ -2,13 +2,15 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class ObjectReferenceTest { @Test - fun createObjectReference() { + fun create() { val objectReference = ObjectReference.builder() .id("id") @@ -17,11 +19,32 @@ internal class ObjectReferenceTest { .objectType(ObjectReference.ObjectType.EXPERIMENT) .created("created") .build() - assertThat(objectReference).isNotNull + assertThat(objectReference.id()).isEqualTo("id") assertThat(objectReference._xactId()).isEqualTo("_xact_id") assertThat(objectReference.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(objectReference.objectType()).isEqualTo(ObjectReference.ObjectType.EXPERIMENT) assertThat(objectReference.created()).contains("created") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val objectReference = + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + + val roundtrippedObjectReference = + jsonMapper.readValue( + jsonMapper.writeValueAsString(objectReference), + jacksonTypeRef(), + ) + + assertThat(roundtrippedObjectReference).isEqualTo(objectReference) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OnlineScoreConfigTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OnlineScoreConfigTest.kt index 01f4d508..9a1a9f83 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OnlineScoreConfigTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OnlineScoreConfigTest.kt @@ -2,13 +2,16 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class OnlineScoreConfigTest { @Test - fun createOnlineScoreConfig() { + fun create() { val onlineScoreConfig = OnlineScoreConfig.builder() .samplingRate(0.0) @@ -21,7 +24,7 @@ internal class OnlineScoreConfigTest { .applyToRootSpan(true) .addApplyToSpanName("string") .build() - assertThat(onlineScoreConfig).isNotNull + assertThat(onlineScoreConfig.samplingRate()).isEqualTo(0.0) assertThat(onlineScoreConfig.scorers()) .containsExactly( @@ -33,6 +36,31 @@ internal class OnlineScoreConfigTest { ) ) assertThat(onlineScoreConfig.applyToRootSpan()).contains(true) - assertThat(onlineScoreConfig.applyToSpanNames().get()).containsExactly("string") + assertThat(onlineScoreConfig.applyToSpanNames().getOrNull()).containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val onlineScoreConfig = + OnlineScoreConfig.builder() + .samplingRate(0.0) + .addScorer( + OnlineScoreConfig.Scorer.Function.builder() + .id("id") + .type(OnlineScoreConfig.Scorer.Function.Type.FUNCTION) + .build() + ) + .applyToRootSpan(true) + .addApplyToSpanName("string") + .build() + + val roundtrippedOnlineScoreConfig = + jsonMapper.readValue( + jsonMapper.writeValueAsString(onlineScoreConfig), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOnlineScoreConfig).isEqualTo(onlineScoreConfig) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationDeleteParamsTest.kt index 7bd8b264..365faa22 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationDeleteParamsTest.kt @@ -15,15 +15,14 @@ internal class OrganizationDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = OrganizationDeleteParams.builder() .organizationId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "organizationId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationListPageResponseTest.kt new file mode 100644 index 00000000..a425684a --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationListPageResponseTest.kt @@ -0,0 +1,70 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class OrganizationListPageResponseTest { + + @Test + fun create() { + val organizationListPageResponse = + OrganizationListPageResponse.builder() + .addObject( + Organization.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .apiUrl("api_url") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .isUniversalApi(true) + .proxyUrl("proxy_url") + .realtimeUrl("realtime_url") + .build() + ) + .build() + + assertThat(organizationListPageResponse.objects()) + .containsExactly( + Organization.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .apiUrl("api_url") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .isUniversalApi(true) + .proxyUrl("proxy_url") + .realtimeUrl("realtime_url") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val organizationListPageResponse = + OrganizationListPageResponse.builder() + .addObject( + Organization.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .apiUrl("api_url") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .isUniversalApi(true) + .proxyUrl("proxy_url") + .realtimeUrl("realtime_url") + .build() + ) + .build() + + val roundtrippedOrganizationListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(organizationListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOrganizationListPageResponse).isEqualTo(organizationListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationMemberUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationMemberUpdateParamsTest.kt index a9430430..bc86325c 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationMemberUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationMemberUpdateParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -60,7 +59,6 @@ internal class OrganizationMemberUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.inviteUsers()) .contains( OrganizationMemberUpdateParams.InviteUsers.builder() @@ -89,7 +87,5 @@ internal class OrganizationMemberUpdateParamsTest { val params = OrganizationMemberUpdateParams.builder().build() val body = params._body() - - assertNotNull(body) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationRetrieveParamsTest.kt index b0f6faaf..bb59a8e4 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationRetrieveParamsTest.kt @@ -15,15 +15,14 @@ internal class OrganizationRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = OrganizationRetrieveParams.builder() .organizationId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "organizationId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationTest.kt index d5220152..83448fde 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationTest.kt @@ -2,6 +2,8 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -9,7 +11,7 @@ import org.junit.jupiter.api.Test internal class OrganizationTest { @Test - fun createOrganization() { + fun create() { val organization = Organization.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -20,7 +22,7 @@ internal class OrganizationTest { .proxyUrl("proxy_url") .realtimeUrl("realtime_url") .build() - assertThat(organization).isNotNull + assertThat(organization.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(organization.name()).isEqualTo("name") assertThat(organization.apiUrl()).contains("api_url") @@ -30,4 +32,27 @@ internal class OrganizationTest { assertThat(organization.proxyUrl()).contains("proxy_url") assertThat(organization.realtimeUrl()).contains("realtime_url") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val organization = + Organization.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .apiUrl("api_url") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .isUniversalApi(true) + .proxyUrl("proxy_url") + .realtimeUrl("realtime_url") + .build() + + val roundtrippedOrganization = + jsonMapper.readValue( + jsonMapper.writeValueAsString(organization), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOrganization).isEqualTo(organization) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationUpdateParamsTest.kt index f1cf977a..a66f513e 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationUpdateParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -20,6 +19,18 @@ internal class OrganizationUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = + OrganizationUpdateParams.builder() + .organizationId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -34,7 +45,6 @@ internal class OrganizationUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.apiUrl()).contains("api_url") assertThat(body.isUniversalApi()).contains(true) assertThat(body.name()).contains("name") @@ -50,20 +60,5 @@ internal class OrganizationUpdateParamsTest { .build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - OrganizationUpdateParams.builder() - .organizationId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - assertThat(params).isNotNull - // path param "organizationId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PatchOrganizationMembersOutputTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PatchOrganizationMembersOutputTest.kt index 8a00b5e5..3afc427b 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PatchOrganizationMembersOutputTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PatchOrganizationMembersOutputTest.kt @@ -2,23 +2,45 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class PatchOrganizationMembersOutputTest { @Test - fun createPatchOrganizationMembersOutput() { + fun create() { val patchOrganizationMembersOutput = PatchOrganizationMembersOutput.builder() .orgId("org_id") .status(PatchOrganizationMembersOutput.Status.SUCCESS) .sendEmailError("send_email_error") .build() - assertThat(patchOrganizationMembersOutput).isNotNull + assertThat(patchOrganizationMembersOutput.orgId()).isEqualTo("org_id") assertThat(patchOrganizationMembersOutput.status()) .isEqualTo(PatchOrganizationMembersOutput.Status.SUCCESS) assertThat(patchOrganizationMembersOutput.sendEmailError()).contains("send_email_error") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val patchOrganizationMembersOutput = + PatchOrganizationMembersOutput.builder() + .orgId("org_id") + .status(PatchOrganizationMembersOutput.Status.SUCCESS) + .sendEmailError("send_email_error") + .build() + + val roundtrippedPatchOrganizationMembersOutput = + jsonMapper.readValue( + jsonMapper.writeValueAsString(patchOrganizationMembersOutput), + jacksonTypeRef(), + ) + + assertThat(roundtrippedPatchOrganizationMembersOutput) + .isEqualTo(patchOrganizationMembersOutput) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectCreateParamsTest.kt index c9ffd874..8751112d 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectCreateParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -19,7 +18,6 @@ internal class ProjectCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") assertThat(body.orgName()).contains("org_name") } @@ -30,7 +28,6 @@ internal class ProjectCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectDeleteParamsTest.kt index 3e30198e..47a71480 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectDeleteParamsTest.kt @@ -13,13 +13,12 @@ internal class ProjectDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = ProjectDeleteParams.builder().projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "projectId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectListPageResponseTest.kt new file mode 100644 index 00000000..1e9fdd55 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectListPageResponseTest.kt @@ -0,0 +1,109 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectListPageResponseTest { + + @Test + fun create() { + val projectListPageResponse = + ProjectListPageResponse.builder() + .addObject( + Project.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .settings( + ProjectSettings.builder() + .baselineExperimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .comparisonKey("comparison_key") + .addSpanFieldOrder( + ProjectSettings.SpanFieldOrder.builder() + .columnId("column_id") + .objectType("object_type") + .position("position") + .layout(ProjectSettings.SpanFieldOrder.Layout.FULL) + .build() + ) + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + assertThat(projectListPageResponse.objects()) + .containsExactly( + Project.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .settings( + ProjectSettings.builder() + .baselineExperimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .comparisonKey("comparison_key") + .addSpanFieldOrder( + ProjectSettings.SpanFieldOrder.builder() + .columnId("column_id") + .objectType("object_type") + .position("position") + .layout(ProjectSettings.SpanFieldOrder.Layout.FULL) + .build() + ) + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val projectListPageResponse = + ProjectListPageResponse.builder() + .addObject( + Project.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .settings( + ProjectSettings.builder() + .baselineExperimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .comparisonKey("comparison_key") + .addSpanFieldOrder( + ProjectSettings.SpanFieldOrder.builder() + .columnId("column_id") + .objectType("object_type") + .position("position") + .layout(ProjectSettings.SpanFieldOrder.Layout.FULL) + .build() + ) + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + val roundtrippedProjectListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(projectListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedProjectListPageResponse).isEqualTo(projectListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFeedbackParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFeedbackParamsTest.kt index 516e71e3..59f797ac 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFeedbackParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFeedbackParamsTest.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -35,6 +34,19 @@ internal class ProjectLogFeedbackParamsTest { .build() } + @Test + fun pathParams() { + val params = + ProjectLogFeedbackParams.builder() + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addFeedback(FeedbackProjectLogsItem.builder().id("id").build()) + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -63,28 +75,25 @@ internal class ProjectLogFeedbackParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.feedback()) - .isEqualTo( - listOf( - FeedbackProjectLogsItem.builder() - .id("id") - .comment("comment") - .expected(JsonValue.from(mapOf())) - .metadata( - FeedbackProjectLogsItem.Metadata.builder() - .putAdditionalProperty("foo", JsonValue.from("bar")) - .build() - ) - .scores( - FeedbackProjectLogsItem.Scores.builder() - .putAdditionalProperty("foo", JsonValue.from(0)) - .build() - ) - .source(FeedbackProjectLogsItem.Source.APP) - .addTag("string") - .build() - ) + .containsExactly( + FeedbackProjectLogsItem.builder() + .id("id") + .comment("comment") + .expected(JsonValue.from(mapOf())) + .metadata( + FeedbackProjectLogsItem.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .scores( + FeedbackProjectLogsItem.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .source(FeedbackProjectLogsItem.Source.APP) + .addTag("string") + .build() ) } @@ -98,22 +107,7 @@ internal class ProjectLogFeedbackParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.feedback()) - .isEqualTo(listOf(FeedbackProjectLogsItem.builder().id("id").build())) - } - - @Test - fun getPathParam() { - val params = - ProjectLogFeedbackParams.builder() - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .addFeedback(FeedbackProjectLogsItem.builder().id("id").build()) - .build() - assertThat(params).isNotNull - // path param "projectId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + .containsExactly(FeedbackProjectLogsItem.builder().id("id").build()) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFetchParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFetchParamsTest.kt index 2f305737..545e215e 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFetchParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFetchParamsTest.kt @@ -19,6 +19,18 @@ internal class ProjectLogFetchParamsTest { .build() } + @Test + fun pathParams() { + val params = + ProjectLogFetchParams.builder() + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun queryParams() { val params = @@ -54,17 +66,4 @@ internal class ProjectLogFetchParamsTest { assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } - - @Test - fun getPathParam() { - val params = - ProjectLogFetchParams.builder() - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - assertThat(params).isNotNull - // path param "projectId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFetchPostParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFetchPostParamsTest.kt index 6bed5b0e..e6c1f8ff 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFetchPostParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFetchPostParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -20,6 +19,18 @@ internal class ProjectLogFetchPostParamsTest { .build() } + @Test + fun pathParams() { + val params = + ProjectLogFetchPostParams.builder() + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -34,7 +45,6 @@ internal class ProjectLogFetchPostParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.cursor()).contains("cursor") assertThat(body.limit()).contains(0L) assertThat(body.maxRootSpanId()).contains("max_root_span_id") @@ -50,20 +60,5 @@ internal class ProjectLogFetchPostParamsTest { .build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - ProjectLogFetchPostParams.builder() - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - assertThat(params).isNotNull - // path param "projectId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogInsertParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogInsertParamsTest.kt index d238976b..1cf5e777 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogInsertParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogInsertParamsTest.kt @@ -4,7 +4,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue import java.time.OffsetDateTime -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -72,6 +71,19 @@ internal class ProjectLogInsertParamsTest { .build() } + @Test + fun pathParams() { + val params = + ProjectLogInsertParams.builder() + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addEvent(InsertProjectLogsEvent.builder().build()) + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -136,64 +148,61 @@ internal class ProjectLogInsertParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.events()) - .isEqualTo( - listOf( - InsertProjectLogsEvent.builder() - .id("id") - ._isMerge(true) - .addMergePath(listOf("string")) - ._objectDelete(true) - ._parentId("_parent_id") - .context( - InsertProjectLogsEvent.Context.builder() - .callerFilename("caller_filename") - .callerFunctionname("caller_functionname") - .callerLineno(0L) - .build() - ) - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .error(JsonValue.from(mapOf())) - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata(InsertProjectLogsEvent.Metadata.builder().model("model").build()) - .metrics( - InsertProjectLogsEvent.Metrics.builder() - .callerFilename(JsonValue.from(mapOf())) - .callerFunctionname(JsonValue.from(mapOf())) - .callerLineno(JsonValue.from(mapOf())) - .completionTokens(0L) - .end(0.0) - .promptTokens(0L) - .start(0.0) - .tokens(0L) - .build() - ) - .origin( - ObjectReference.builder() - .id("id") - ._xactId("_xact_id") - .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .objectType(ObjectReference.ObjectType.EXPERIMENT) - .created("created") - .build() - ) - .output(JsonValue.from(mapOf())) - .rootSpanId("root_span_id") - .scores( - InsertProjectLogsEvent.Scores.builder() - .putAdditionalProperty("foo", JsonValue.from(0)) - .build() - ) - .spanAttributes( - SpanAttributes.builder().name("name").type(SpanType.LLM).build() - ) - .spanId("span_id") - .addSpanParent("string") - .addTag("string") - .build() - ) + .containsExactly( + InsertProjectLogsEvent.builder() + .id("id") + ._isMerge(true) + .addMergePath(listOf("string")) + ._objectDelete(true) + ._parentId("_parent_id") + .context( + InsertProjectLogsEvent.Context.builder() + .callerFilename("caller_filename") + .callerFunctionname("caller_functionname") + .callerLineno(0L) + .build() + ) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .error(JsonValue.from(mapOf())) + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .metadata(InsertProjectLogsEvent.Metadata.builder().model("model").build()) + .metrics( + InsertProjectLogsEvent.Metrics.builder() + .callerFilename(JsonValue.from(mapOf())) + .callerFunctionname(JsonValue.from(mapOf())) + .callerLineno(JsonValue.from(mapOf())) + .completionTokens(0L) + .end(0.0) + .promptTokens(0L) + .start(0.0) + .tokens(0L) + .build() + ) + .origin( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + .output(JsonValue.from(mapOf())) + .rootSpanId("root_span_id") + .scores( + InsertProjectLogsEvent.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .spanAttributes( + SpanAttributes.builder().name("name").type(SpanType.LLM).build() + ) + .spanId("span_id") + .addSpanParent("string") + .addTag("string") + .build() ) } @@ -207,21 +216,6 @@ internal class ProjectLogInsertParamsTest { val body = params._body() - assertNotNull(body) - assertThat(body.events()).isEqualTo(listOf(InsertProjectLogsEvent.builder().build())) - } - - @Test - fun getPathParam() { - val params = - ProjectLogInsertParams.builder() - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .addEvent(InsertProjectLogsEvent.builder().build()) - .build() - assertThat(params).isNotNull - // path param "projectId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(body.events()).containsExactly(InsertProjectLogsEvent.builder().build()) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogsEventTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogsEventTest.kt index ac983318..e91f1d39 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogsEventTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogsEventTest.kt @@ -3,14 +3,17 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class ProjectLogsEventTest { @Test - fun createProjectLogsEvent() { + fun create() { val projectLogsEvent = ProjectLogsEvent.builder() .id("id") @@ -64,7 +67,7 @@ internal class ProjectLogsEventTest { .addSpanParent("string") .addTag("string") .build() - assertThat(projectLogsEvent).isNotNull + assertThat(projectLogsEvent.id()).isEqualTo("id") assertThat(projectLogsEvent._xactId()).isEqualTo("_xact_id") assertThat(projectLogsEvent.created()) @@ -120,7 +123,73 @@ internal class ProjectLogsEventTest { ) assertThat(projectLogsEvent.spanAttributes()) .contains(SpanAttributes.builder().name("name").type(SpanType.LLM).build()) - assertThat(projectLogsEvent.spanParents().get()).containsExactly("string") - assertThat(projectLogsEvent.tags().get()).containsExactly("string") + assertThat(projectLogsEvent.spanParents().getOrNull()).containsExactly("string") + assertThat(projectLogsEvent.tags().getOrNull()).containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val projectLogsEvent = + ProjectLogsEvent.builder() + .id("id") + ._xactId("_xact_id") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .logId(ProjectLogsEvent.LogId.G) + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .rootSpanId("root_span_id") + .spanId("span_id") + .context( + ProjectLogsEvent.Context.builder() + .callerFilename("caller_filename") + .callerFunctionname("caller_functionname") + .callerLineno(0L) + .build() + ) + .error(JsonValue.from(mapOf())) + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .isRoot(true) + .metadata(ProjectLogsEvent.Metadata.builder().model("model").build()) + .metrics( + ProjectLogsEvent.Metrics.builder() + .callerFilename(JsonValue.from(mapOf())) + .callerFunctionname(JsonValue.from(mapOf())) + .callerLineno(JsonValue.from(mapOf())) + .completionTokens(0L) + .end(0.0) + .promptTokens(0L) + .start(0.0) + .tokens(0L) + .build() + ) + .origin( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + .output(JsonValue.from(mapOf())) + .scores( + ProjectLogsEvent.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .spanAttributes(SpanAttributes.builder().name("name").type(SpanType.LLM).build()) + .addSpanParent("string") + .addTag("string") + .build() + + val roundtrippedProjectLogsEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(projectLogsEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedProjectLogsEvent).isEqualTo(projectLogsEvent) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectRetrieveParamsTest.kt index ad7bf543..e83306b3 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectRetrieveParamsTest.kt @@ -13,15 +13,14 @@ internal class ProjectRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = ProjectRetrieveParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "projectId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreCategoryTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreCategoryTest.kt index eb62ebe7..3e4d1ce0 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreCategoryTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreCategoryTest.kt @@ -2,16 +2,32 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class ProjectScoreCategoryTest { @Test - fun createProjectScoreCategory() { + fun create() { val projectScoreCategory = ProjectScoreCategory.builder().name("name").value(0.0).build() - assertThat(projectScoreCategory).isNotNull + assertThat(projectScoreCategory.name()).isEqualTo("name") assertThat(projectScoreCategory.value()).isEqualTo(0.0) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val projectScoreCategory = ProjectScoreCategory.builder().name("name").value(0.0).build() + + val roundtrippedProjectScoreCategory = + jsonMapper.readValue( + jsonMapper.writeValueAsString(projectScoreCategory), + jacksonTypeRef(), + ) + + assertThat(roundtrippedProjectScoreCategory).isEqualTo(projectScoreCategory) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreConfigTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreConfigTest.kt index 40346457..613487b8 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreConfigTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreConfigTest.kt @@ -2,13 +2,15 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class ProjectScoreConfigTest { @Test - fun createProjectScoreConfig() { + fun create() { val projectScoreConfig = ProjectScoreConfig.builder() .destination("destination") @@ -27,7 +29,7 @@ internal class ProjectScoreConfigTest { .build() ) .build() - assertThat(projectScoreConfig).isNotNull + assertThat(projectScoreConfig.destination()).contains("destination") assertThat(projectScoreConfig.multiSelect()).contains(true) assertThat(projectScoreConfig.online()) @@ -45,4 +47,35 @@ internal class ProjectScoreConfigTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val projectScoreConfig = + ProjectScoreConfig.builder() + .destination("destination") + .multiSelect(true) + .online( + OnlineScoreConfig.builder() + .samplingRate(0.0) + .addScorer( + OnlineScoreConfig.Scorer.Function.builder() + .id("id") + .type(OnlineScoreConfig.Scorer.Function.Type.FUNCTION) + .build() + ) + .applyToRootSpan(true) + .addApplyToSpanName("string") + .build() + ) + .build() + + val roundtrippedProjectScoreConfig = + jsonMapper.readValue( + jsonMapper.writeValueAsString(projectScoreConfig), + jacksonTypeRef(), + ) + + assertThat(roundtrippedProjectScoreConfig).isEqualTo(projectScoreConfig) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreCreateParamsTest.kt index af4c04c3..a192a789 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreCreateParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -74,7 +73,6 @@ internal class ProjectScoreCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.scoreType()).isEqualTo(ProjectScoreType.SLIDER) @@ -118,7 +116,6 @@ internal class ProjectScoreCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.scoreType()).isEqualTo(ProjectScoreType.SLIDER) diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreDeleteParamsTest.kt index 3ba5951f..c90b6173 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreDeleteParamsTest.kt @@ -15,15 +15,14 @@ internal class ProjectScoreDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = ProjectScoreDeleteParams.builder() .projectScoreId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "projectScoreId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreListPageResponseTest.kt new file mode 100644 index 00000000..27b1a1d2 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreListPageResponseTest.kt @@ -0,0 +1,143 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectScoreListPageResponseTest { + + @Test + fun create() { + val projectScoreListPageResponse = + ProjectScoreListPageResponse.builder() + .addObject( + ProjectScore.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .scoreType(ProjectScoreType.SLIDER) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .categoriesOfCategorical( + listOf(ProjectScoreCategory.builder().name("name").value(0.0).build()) + ) + .config( + ProjectScoreConfig.builder() + .destination("destination") + .multiSelect(true) + .online( + OnlineScoreConfig.builder() + .samplingRate(0.0) + .addScorer( + OnlineScoreConfig.Scorer.Function.builder() + .id("id") + .type( + OnlineScoreConfig.Scorer.Function.Type.FUNCTION + ) + .build() + ) + .applyToRootSpan(true) + .addApplyToSpanName("string") + .build() + ) + .build() + ) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .position("position") + .build() + ) + .build() + + assertThat(projectScoreListPageResponse.objects()) + .containsExactly( + ProjectScore.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .scoreType(ProjectScoreType.SLIDER) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .categoriesOfCategorical( + listOf(ProjectScoreCategory.builder().name("name").value(0.0).build()) + ) + .config( + ProjectScoreConfig.builder() + .destination("destination") + .multiSelect(true) + .online( + OnlineScoreConfig.builder() + .samplingRate(0.0) + .addScorer( + OnlineScoreConfig.Scorer.Function.builder() + .id("id") + .type(OnlineScoreConfig.Scorer.Function.Type.FUNCTION) + .build() + ) + .applyToRootSpan(true) + .addApplyToSpanName("string") + .build() + ) + .build() + ) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .position("position") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val projectScoreListPageResponse = + ProjectScoreListPageResponse.builder() + .addObject( + ProjectScore.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .scoreType(ProjectScoreType.SLIDER) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .categoriesOfCategorical( + listOf(ProjectScoreCategory.builder().name("name").value(0.0).build()) + ) + .config( + ProjectScoreConfig.builder() + .destination("destination") + .multiSelect(true) + .online( + OnlineScoreConfig.builder() + .samplingRate(0.0) + .addScorer( + OnlineScoreConfig.Scorer.Function.builder() + .id("id") + .type( + OnlineScoreConfig.Scorer.Function.Type.FUNCTION + ) + .build() + ) + .applyToRootSpan(true) + .addApplyToSpanName("string") + .build() + ) + .build() + ) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .position("position") + .build() + ) + .build() + + val roundtrippedProjectScoreListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(projectScoreListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedProjectScoreListPageResponse).isEqualTo(projectScoreListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreReplaceParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreReplaceParamsTest.kt index 50960ecf..b569d015 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreReplaceParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreReplaceParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -74,7 +73,6 @@ internal class ProjectScoreReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.scoreType()).isEqualTo(ProjectScoreType.SLIDER) @@ -118,7 +116,6 @@ internal class ProjectScoreReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.scoreType()).isEqualTo(ProjectScoreType.SLIDER) diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreRetrieveParamsTest.kt index a6f2bd61..8bfde8f2 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreRetrieveParamsTest.kt @@ -15,15 +15,14 @@ internal class ProjectScoreRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = ProjectScoreRetrieveParams.builder() .projectScoreId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "projectScoreId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreTest.kt index 576f47a4..3fc8a833 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreTest.kt @@ -2,6 +2,8 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -9,7 +11,7 @@ import org.junit.jupiter.api.Test internal class ProjectScoreTest { @Test - fun createProjectScore() { + fun create() { val projectScore = ProjectScore.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -43,7 +45,7 @@ internal class ProjectScoreTest { .description("description") .position("position") .build() - assertThat(projectScore).isNotNull + assertThat(projectScore.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(projectScore.name()).isEqualTo("name") assertThat(projectScore.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -80,4 +82,50 @@ internal class ProjectScoreTest { assertThat(projectScore.description()).contains("description") assertThat(projectScore.position()).contains("position") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val projectScore = + ProjectScore.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .scoreType(ProjectScoreType.SLIDER) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .categoriesOfCategorical( + listOf(ProjectScoreCategory.builder().name("name").value(0.0).build()) + ) + .config( + ProjectScoreConfig.builder() + .destination("destination") + .multiSelect(true) + .online( + OnlineScoreConfig.builder() + .samplingRate(0.0) + .addScorer( + OnlineScoreConfig.Scorer.Function.builder() + .id("id") + .type(OnlineScoreConfig.Scorer.Function.Type.FUNCTION) + .build() + ) + .applyToRootSpan(true) + .addApplyToSpanName("string") + .build() + ) + .build() + ) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .position("position") + .build() + + val roundtrippedProjectScore = + jsonMapper.readValue( + jsonMapper.writeValueAsString(projectScore), + jacksonTypeRef(), + ) + + assertThat(roundtrippedProjectScore).isEqualTo(projectScore) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreUpdateParamsTest.kt index 5c2a615d..1feddf2e 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreUpdateParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -40,6 +39,18 @@ internal class ProjectScoreUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = + ProjectScoreUpdateParams.builder() + .projectScoreId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -74,7 +85,6 @@ internal class ProjectScoreUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.categories()) .contains( ProjectScoreUpdateParams.Categories.ofCategorical( @@ -114,20 +124,5 @@ internal class ProjectScoreUpdateParamsTest { .build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - ProjectScoreUpdateParams.builder() - .projectScoreId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - assertThat(params).isNotNull - // path param "projectScoreId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectSettingsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectSettingsTest.kt index 7a9c2f21..3d5015d9 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectSettingsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectSettingsTest.kt @@ -2,13 +2,16 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class ProjectSettingsTest { @Test - fun createProjectSettings() { + fun create() { val projectSettings = ProjectSettings.builder() .baselineExperimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -22,11 +25,11 @@ internal class ProjectSettingsTest { .build() ) .build() - assertThat(projectSettings).isNotNull + assertThat(projectSettings.baselineExperimentId()) .contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(projectSettings.comparisonKey()).contains("comparison_key") - assertThat(projectSettings.spanFieldOrder().get()) + assertThat(projectSettings.spanFieldOrder().getOrNull()) .containsExactly( ProjectSettings.SpanFieldOrder.builder() .columnId("column_id") @@ -36,4 +39,30 @@ internal class ProjectSettingsTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val projectSettings = + ProjectSettings.builder() + .baselineExperimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .comparisonKey("comparison_key") + .addSpanFieldOrder( + ProjectSettings.SpanFieldOrder.builder() + .columnId("column_id") + .objectType("object_type") + .position("position") + .layout(ProjectSettings.SpanFieldOrder.Layout.FULL) + .build() + ) + .build() + + val roundtrippedProjectSettings = + jsonMapper.readValue( + jsonMapper.writeValueAsString(projectSettings), + jacksonTypeRef(), + ) + + assertThat(roundtrippedProjectSettings).isEqualTo(projectSettings) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagCreateParamsTest.kt index 221e1eb7..c738ab63 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagCreateParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -30,7 +29,6 @@ internal class ProjectTagCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.color()).contains("color") @@ -47,7 +45,6 @@ internal class ProjectTagCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagDeleteParamsTest.kt index 7de39ed3..16087334 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagDeleteParamsTest.kt @@ -15,15 +15,14 @@ internal class ProjectTagDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = ProjectTagDeleteParams.builder() .projectTagId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "projectTagId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagListPageResponseTest.kt new file mode 100644 index 00000000..4dd2fc1f --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagListPageResponseTest.kt @@ -0,0 +1,70 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectTagListPageResponseTest { + + @Test + fun create() { + val projectTagListPageResponse = + ProjectTagListPageResponse.builder() + .addObject( + ProjectTag.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .build() + ) + .build() + + assertThat(projectTagListPageResponse.objects()) + .containsExactly( + ProjectTag.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val projectTagListPageResponse = + ProjectTagListPageResponse.builder() + .addObject( + ProjectTag.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .build() + ) + .build() + + val roundtrippedProjectTagListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(projectTagListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedProjectTagListPageResponse).isEqualTo(projectTagListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagReplaceParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagReplaceParamsTest.kt index c3c2cb8c..39eae201 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagReplaceParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagReplaceParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -30,7 +29,6 @@ internal class ProjectTagReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.color()).contains("color") @@ -47,7 +45,6 @@ internal class ProjectTagReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagRetrieveParamsTest.kt index bceb5438..f7bbf553 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagRetrieveParamsTest.kt @@ -15,15 +15,14 @@ internal class ProjectTagRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = ProjectTagRetrieveParams.builder() .projectTagId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "projectTagId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagTest.kt index 23968bbb..efeaf87b 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagTest.kt @@ -2,6 +2,8 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -9,7 +11,7 @@ import org.junit.jupiter.api.Test internal class ProjectTagTest { @Test - fun createProjectTag() { + fun create() { val projectTag = ProjectTag.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -20,7 +22,7 @@ internal class ProjectTagTest { .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) .description("description") .build() - assertThat(projectTag).isNotNull + assertThat(projectTag.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(projectTag.name()).isEqualTo("name") assertThat(projectTag.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -29,4 +31,27 @@ internal class ProjectTagTest { assertThat(projectTag.created()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) assertThat(projectTag.description()).contains("description") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val projectTag = + ProjectTag.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .build() + + val roundtrippedProjectTag = + jsonMapper.readValue( + jsonMapper.writeValueAsString(projectTag), + jacksonTypeRef(), + ) + + assertThat(roundtrippedProjectTag).isEqualTo(projectTag) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagUpdateParamsTest.kt index 0bda9b77..beb3b668 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagUpdateParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -18,6 +17,18 @@ internal class ProjectTagUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = + ProjectTagUpdateParams.builder() + .projectTagId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -30,7 +41,6 @@ internal class ProjectTagUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.color()).contains("color") assertThat(body.description()).contains("description") assertThat(body.name()).contains("name") @@ -44,20 +54,5 @@ internal class ProjectTagUpdateParamsTest { .build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - ProjectTagUpdateParams.builder() - .projectTagId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - assertThat(params).isNotNull - // path param "projectTagId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTest.kt index 15ac6b29..59c7821f 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTest.kt @@ -2,6 +2,8 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -9,7 +11,7 @@ import org.junit.jupiter.api.Test internal class ProjectTest { @Test - fun createProject() { + fun create() { val project = Project.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -33,7 +35,7 @@ internal class ProjectTest { ) .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(project).isNotNull + assertThat(project.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(project.name()).isEqualTo("name") assertThat(project.orgId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -56,4 +58,37 @@ internal class ProjectTest { ) assertThat(project.userId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val project = + Project.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .settings( + ProjectSettings.builder() + .baselineExperimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .comparisonKey("comparison_key") + .addSpanFieldOrder( + ProjectSettings.SpanFieldOrder.builder() + .columnId("column_id") + .objectType("object_type") + .position("position") + .layout(ProjectSettings.SpanFieldOrder.Layout.FULL) + .build() + ) + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val roundtrippedProject = + jsonMapper.readValue(jsonMapper.writeValueAsString(project), jacksonTypeRef()) + + assertThat(roundtrippedProject).isEqualTo(project) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectUpdateParamsTest.kt index 231a5855..99b062a2 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectUpdateParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -30,6 +29,16 @@ internal class ProjectUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = + ProjectUpdateParams.builder().projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -54,7 +63,6 @@ internal class ProjectUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).contains("name") assertThat(body.settings()) .contains( @@ -79,18 +87,5 @@ internal class ProjectUpdateParamsTest { ProjectUpdateParams.builder().projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - ProjectUpdateParams.builder().projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "projectId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptCreateParamsTest.kt index 4b481b7f..8013fd96 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptCreateParamsTest.kt @@ -3,7 +3,7 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -194,7 +194,6 @@ internal class PromptCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.slug()).isEqualTo("x") @@ -280,7 +279,7 @@ internal class PromptCreateParamsTest { ) .build() ) - assertThat(body.tags()).contains(listOf("string")) + assertThat(body.tags().getOrNull()).containsExactly("string") } @Test @@ -294,7 +293,6 @@ internal class PromptCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.slug()).isEqualTo("x") diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptDataTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptDataTest.kt index 88789045..97966fac 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptDataTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptDataTest.kt @@ -3,13 +3,16 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class PromptDataTest { @Test - fun createPromptData() { + fun create() { val promptData = PromptData.builder() .options( @@ -84,7 +87,7 @@ internal class PromptDataTest { .build() ) .build() - assertThat(promptData).isNotNull + assertThat(promptData.options()) .contains( PromptOptions.builder() @@ -155,7 +158,7 @@ internal class PromptDataTest { .build() ) ) - assertThat(promptData.toolFunctions().get()) + assertThat(promptData.toolFunctions().getOrNull()) .containsExactly( PromptData.ToolFunction.ofFunction( PromptData.ToolFunction.Function.builder() @@ -165,4 +168,91 @@ internal class PromptDataTest { ) ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val promptData = + PromptData.builder() + .options( + PromptOptions.builder() + .model("model") + .params( + PromptOptions.Params.OpenAIModelParams.builder() + .frequencyPenalty(0.0) + .functionCall( + PromptOptions.Params.OpenAIModelParams.FunctionCall.UnionMember0 + .AUTO + ) + .maxCompletionTokens(0.0) + .maxTokens(0.0) + .n(0.0) + .presencePenalty(0.0) + .reasoningEffort( + PromptOptions.Params.OpenAIModelParams.ReasoningEffort.LOW + ) + .responseFormat( + PromptOptions.Params.OpenAIModelParams.ResponseFormat.JsonObject + .builder() + .type( + PromptOptions.Params.OpenAIModelParams.ResponseFormat + .JsonObject + .Type + .JSON_OBJECT + ) + .build() + ) + .addStop("string") + .temperature(0.0) + .toolChoice( + PromptOptions.Params.OpenAIModelParams.ToolChoice.UnionMember0 + .AUTO + ) + .topP(0.0) + .useCache(true) + .build() + ) + .position("position") + .build() + ) + .origin( + PromptData.Origin.builder() + .projectId("project_id") + .promptId("prompt_id") + .promptVersion("prompt_version") + .build() + ) + .parser( + PromptData.Parser.builder() + .choiceScores( + PromptData.Parser.ChoiceScores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .type(PromptData.Parser.Type.LLM_CLASSIFIER) + .useCot(true) + .build() + ) + .prompt( + PromptData.Prompt.Completion.builder() + .content("content") + .type(PromptData.Prompt.Completion.Type.COMPLETION) + .build() + ) + .addToolFunction( + PromptData.ToolFunction.Function.builder() + .id("id") + .type(PromptData.ToolFunction.Function.Type.FUNCTION) + .build() + ) + .build() + + val roundtrippedPromptData = + jsonMapper.readValue( + jsonMapper.writeValueAsString(promptData), + jacksonTypeRef(), + ) + + assertThat(roundtrippedPromptData).isEqualTo(promptData) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptDeleteParamsTest.kt index 5fa9d727..45b20f34 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptDeleteParamsTest.kt @@ -13,13 +13,12 @@ internal class PromptDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = PromptDeleteParams.builder().promptId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "promptId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptListPageResponseTest.kt new file mode 100644 index 00000000..9894bafc --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptListPageResponseTest.kt @@ -0,0 +1,348 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class PromptListPageResponseTest { + + @Test + fun create() { + val promptListPageResponse = + PromptListPageResponse.builder() + .addObject( + Prompt.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + ._xactId("_xact_id") + .logId(Prompt.LogId.P) + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("slug") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .functionType(Prompt.FunctionType.LLM) + .metadata( + Prompt.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .promptData( + PromptData.builder() + .options( + PromptOptions.builder() + .model("model") + .params( + PromptOptions.Params.OpenAIModelParams.builder() + .frequencyPenalty(0.0) + .functionCall( + PromptOptions.Params.OpenAIModelParams + .FunctionCall + .UnionMember0 + .AUTO + ) + .maxCompletionTokens(0.0) + .maxTokens(0.0) + .n(0.0) + .presencePenalty(0.0) + .reasoningEffort( + PromptOptions.Params.OpenAIModelParams + .ReasoningEffort + .LOW + ) + .responseFormat( + PromptOptions.Params.OpenAIModelParams + .ResponseFormat + .JsonObject + .builder() + .type( + PromptOptions.Params.OpenAIModelParams + .ResponseFormat + .JsonObject + .Type + .JSON_OBJECT + ) + .build() + ) + .addStop("string") + .temperature(0.0) + .toolChoice( + PromptOptions.Params.OpenAIModelParams + .ToolChoice + .UnionMember0 + .AUTO + ) + .topP(0.0) + .useCache(true) + .build() + ) + .position("position") + .build() + ) + .origin( + PromptData.Origin.builder() + .projectId("project_id") + .promptId("prompt_id") + .promptVersion("prompt_version") + .build() + ) + .parser( + PromptData.Parser.builder() + .choiceScores( + PromptData.Parser.ChoiceScores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .type(PromptData.Parser.Type.LLM_CLASSIFIER) + .useCot(true) + .build() + ) + .prompt( + PromptData.Prompt.Completion.builder() + .content("content") + .type(PromptData.Prompt.Completion.Type.COMPLETION) + .build() + ) + .addToolFunction( + PromptData.ToolFunction.Function.builder() + .id("id") + .type(PromptData.ToolFunction.Function.Type.FUNCTION) + .build() + ) + .build() + ) + .addTag("string") + .build() + ) + .build() + + assertThat(promptListPageResponse.objects()) + .containsExactly( + Prompt.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + ._xactId("_xact_id") + .logId(Prompt.LogId.P) + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("slug") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .functionType(Prompt.FunctionType.LLM) + .metadata( + Prompt.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .promptData( + PromptData.builder() + .options( + PromptOptions.builder() + .model("model") + .params( + PromptOptions.Params.OpenAIModelParams.builder() + .frequencyPenalty(0.0) + .functionCall( + PromptOptions.Params.OpenAIModelParams.FunctionCall + .UnionMember0 + .AUTO + ) + .maxCompletionTokens(0.0) + .maxTokens(0.0) + .n(0.0) + .presencePenalty(0.0) + .reasoningEffort( + PromptOptions.Params.OpenAIModelParams + .ReasoningEffort + .LOW + ) + .responseFormat( + PromptOptions.Params.OpenAIModelParams + .ResponseFormat + .JsonObject + .builder() + .type( + PromptOptions.Params.OpenAIModelParams + .ResponseFormat + .JsonObject + .Type + .JSON_OBJECT + ) + .build() + ) + .addStop("string") + .temperature(0.0) + .toolChoice( + PromptOptions.Params.OpenAIModelParams.ToolChoice + .UnionMember0 + .AUTO + ) + .topP(0.0) + .useCache(true) + .build() + ) + .position("position") + .build() + ) + .origin( + PromptData.Origin.builder() + .projectId("project_id") + .promptId("prompt_id") + .promptVersion("prompt_version") + .build() + ) + .parser( + PromptData.Parser.builder() + .choiceScores( + PromptData.Parser.ChoiceScores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .type(PromptData.Parser.Type.LLM_CLASSIFIER) + .useCot(true) + .build() + ) + .prompt( + PromptData.Prompt.Completion.builder() + .content("content") + .type(PromptData.Prompt.Completion.Type.COMPLETION) + .build() + ) + .addToolFunction( + PromptData.ToolFunction.Function.builder() + .id("id") + .type(PromptData.ToolFunction.Function.Type.FUNCTION) + .build() + ) + .build() + ) + .addTag("string") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val promptListPageResponse = + PromptListPageResponse.builder() + .addObject( + Prompt.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + ._xactId("_xact_id") + .logId(Prompt.LogId.P) + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("slug") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .functionType(Prompt.FunctionType.LLM) + .metadata( + Prompt.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .promptData( + PromptData.builder() + .options( + PromptOptions.builder() + .model("model") + .params( + PromptOptions.Params.OpenAIModelParams.builder() + .frequencyPenalty(0.0) + .functionCall( + PromptOptions.Params.OpenAIModelParams + .FunctionCall + .UnionMember0 + .AUTO + ) + .maxCompletionTokens(0.0) + .maxTokens(0.0) + .n(0.0) + .presencePenalty(0.0) + .reasoningEffort( + PromptOptions.Params.OpenAIModelParams + .ReasoningEffort + .LOW + ) + .responseFormat( + PromptOptions.Params.OpenAIModelParams + .ResponseFormat + .JsonObject + .builder() + .type( + PromptOptions.Params.OpenAIModelParams + .ResponseFormat + .JsonObject + .Type + .JSON_OBJECT + ) + .build() + ) + .addStop("string") + .temperature(0.0) + .toolChoice( + PromptOptions.Params.OpenAIModelParams + .ToolChoice + .UnionMember0 + .AUTO + ) + .topP(0.0) + .useCache(true) + .build() + ) + .position("position") + .build() + ) + .origin( + PromptData.Origin.builder() + .projectId("project_id") + .promptId("prompt_id") + .promptVersion("prompt_version") + .build() + ) + .parser( + PromptData.Parser.builder() + .choiceScores( + PromptData.Parser.ChoiceScores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .type(PromptData.Parser.Type.LLM_CLASSIFIER) + .useCot(true) + .build() + ) + .prompt( + PromptData.Prompt.Completion.builder() + .content("content") + .type(PromptData.Prompt.Completion.Type.COMPLETION) + .build() + ) + .addToolFunction( + PromptData.ToolFunction.Function.builder() + .id("id") + .type(PromptData.ToolFunction.Function.Type.FUNCTION) + .build() + ) + .build() + ) + .addTag("string") + .build() + ) + .build() + + val roundtrippedPromptListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(promptListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedPromptListPageResponse).isEqualTo(promptListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptOptionsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptOptionsTest.kt index 05a4e211..46cf6e9a 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptOptionsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptOptionsTest.kt @@ -2,13 +2,15 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class PromptOptionsTest { @Test - fun createPromptOptions() { + fun create() { val promptOptions = PromptOptions.builder() .model("model") @@ -44,7 +46,7 @@ internal class PromptOptionsTest { ) .position("position") .build() - assertThat(promptOptions).isNotNull + assertThat(promptOptions.model()).contains("model") assertThat(promptOptions.params()) .contains( @@ -81,4 +83,52 @@ internal class PromptOptionsTest { ) assertThat(promptOptions.position()).contains("position") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val promptOptions = + PromptOptions.builder() + .model("model") + .params( + PromptOptions.Params.OpenAIModelParams.builder() + .frequencyPenalty(0.0) + .functionCall( + PromptOptions.Params.OpenAIModelParams.FunctionCall.UnionMember0.AUTO + ) + .maxCompletionTokens(0.0) + .maxTokens(0.0) + .n(0.0) + .presencePenalty(0.0) + .reasoningEffort(PromptOptions.Params.OpenAIModelParams.ReasoningEffort.LOW) + .responseFormat( + PromptOptions.Params.OpenAIModelParams.ResponseFormat.JsonObject + .builder() + .type( + PromptOptions.Params.OpenAIModelParams.ResponseFormat.JsonObject + .Type + .JSON_OBJECT + ) + .build() + ) + .addStop("string") + .temperature(0.0) + .toolChoice( + PromptOptions.Params.OpenAIModelParams.ToolChoice.UnionMember0.AUTO + ) + .topP(0.0) + .useCache(true) + .build() + ) + .position("position") + .build() + + val roundtrippedPromptOptions = + jsonMapper.readValue( + jsonMapper.writeValueAsString(promptOptions), + jacksonTypeRef(), + ) + + assertThat(roundtrippedPromptOptions).isEqualTo(promptOptions) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptReplaceParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptReplaceParamsTest.kt index a3b083cf..2b627b25 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptReplaceParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptReplaceParamsTest.kt @@ -3,7 +3,7 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -194,7 +194,6 @@ internal class PromptReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.slug()).isEqualTo("x") @@ -280,7 +279,7 @@ internal class PromptReplaceParamsTest { ) .build() ) - assertThat(body.tags()).contains(listOf("string")) + assertThat(body.tags().getOrNull()).containsExactly("string") } @Test @@ -294,7 +293,6 @@ internal class PromptReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.slug()).isEqualTo("x") diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptRetrieveParamsTest.kt index a5915832..97f8cb26 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptRetrieveParamsTest.kt @@ -13,13 +13,12 @@ internal class PromptRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = PromptRetrieveParams.builder().promptId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "promptId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptTest.kt index 15360d72..0928b7d9 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptTest.kt @@ -3,14 +3,17 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class PromptTest { @Test - fun createPrompt() { + fun create() { val prompt = Prompt.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -110,7 +113,7 @@ internal class PromptTest { ) .addTag("string") .build() - assertThat(prompt).isNotNull + assertThat(prompt.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(prompt._xactId()).isEqualTo("_xact_id") assertThat(prompt.logId()).isEqualTo(Prompt.LogId.P) @@ -207,6 +210,115 @@ internal class PromptTest { ) .build() ) - assertThat(prompt.tags().get()).containsExactly("string") + assertThat(prompt.tags().getOrNull()).containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val prompt = + Prompt.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + ._xactId("_xact_id") + .logId(Prompt.LogId.P) + .name("name") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("slug") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .functionType(Prompt.FunctionType.LLM) + .metadata( + Prompt.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .promptData( + PromptData.builder() + .options( + PromptOptions.builder() + .model("model") + .params( + PromptOptions.Params.OpenAIModelParams.builder() + .frequencyPenalty(0.0) + .functionCall( + PromptOptions.Params.OpenAIModelParams.FunctionCall + .UnionMember0 + .AUTO + ) + .maxCompletionTokens(0.0) + .maxTokens(0.0) + .n(0.0) + .presencePenalty(0.0) + .reasoningEffort( + PromptOptions.Params.OpenAIModelParams.ReasoningEffort + .LOW + ) + .responseFormat( + PromptOptions.Params.OpenAIModelParams.ResponseFormat + .JsonObject + .builder() + .type( + PromptOptions.Params.OpenAIModelParams + .ResponseFormat + .JsonObject + .Type + .JSON_OBJECT + ) + .build() + ) + .addStop("string") + .temperature(0.0) + .toolChoice( + PromptOptions.Params.OpenAIModelParams.ToolChoice + .UnionMember0 + .AUTO + ) + .topP(0.0) + .useCache(true) + .build() + ) + .position("position") + .build() + ) + .origin( + PromptData.Origin.builder() + .projectId("project_id") + .promptId("prompt_id") + .promptVersion("prompt_version") + .build() + ) + .parser( + PromptData.Parser.builder() + .choiceScores( + PromptData.Parser.ChoiceScores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .type(PromptData.Parser.Type.LLM_CLASSIFIER) + .useCot(true) + .build() + ) + .prompt( + PromptData.Prompt.Completion.builder() + .content("content") + .type(PromptData.Prompt.Completion.Type.COMPLETION) + .build() + ) + .addToolFunction( + PromptData.ToolFunction.Function.builder() + .id("id") + .type(PromptData.ToolFunction.Function.Type.FUNCTION) + .build() + ) + .build() + ) + .addTag("string") + .build() + + val roundtrippedPrompt = + jsonMapper.readValue(jsonMapper.writeValueAsString(prompt), jacksonTypeRef()) + + assertThat(roundtrippedPrompt).isEqualTo(prompt) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptUpdateParamsTest.kt index 70bfe5a7..43dfac44 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptUpdateParamsTest.kt @@ -3,7 +3,7 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -99,6 +99,16 @@ internal class PromptUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = + PromptUpdateParams.builder().promptId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -192,7 +202,6 @@ internal class PromptUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.description()).contains("description") assertThat(body.name()).contains("name") assertThat(body.promptData()) @@ -276,7 +285,7 @@ internal class PromptUpdateParamsTest { .build() ) assertThat(body.slug()).contains("slug") - assertThat(body.tags()).contains(listOf("string")) + assertThat(body.tags().getOrNull()).containsExactly("string") } @Test @@ -285,18 +294,5 @@ internal class PromptUpdateParamsTest { PromptUpdateParams.builder().promptId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - PromptUpdateParams.builder().promptId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "promptId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RepoInfoTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RepoInfoTest.kt index 402272fd..8c8ccdc8 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RepoInfoTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RepoInfoTest.kt @@ -2,13 +2,15 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class RepoInfoTest { @Test - fun createRepoInfo() { + fun create() { val repoInfo = RepoInfo.builder() .authorEmail("author_email") @@ -21,7 +23,7 @@ internal class RepoInfoTest { .gitDiff("git_diff") .tag("tag") .build() - assertThat(repoInfo).isNotNull + assertThat(repoInfo.authorEmail()).contains("author_email") assertThat(repoInfo.authorName()).contains("author_name") assertThat(repoInfo.branch()).contains("branch") @@ -32,4 +34,29 @@ internal class RepoInfoTest { assertThat(repoInfo.gitDiff()).contains("git_diff") assertThat(repoInfo.tag()).contains("tag") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val repoInfo = + RepoInfo.builder() + .authorEmail("author_email") + .authorName("author_name") + .branch("branch") + .commit("commit") + .commitMessage("commit_message") + .commitTime("commit_time") + .dirty(true) + .gitDiff("git_diff") + .tag("tag") + .build() + + val roundtrippedRepoInfo = + jsonMapper.readValue( + jsonMapper.writeValueAsString(repoInfo), + jacksonTypeRef(), + ) + + assertThat(roundtrippedRepoInfo).isEqualTo(repoInfo) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleCreateParamsTest.kt index 9310f639..74b23cad 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleCreateParamsTest.kt @@ -2,7 +2,7 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -42,19 +42,17 @@ internal class RoleCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") assertThat(body.description()).contains("description") - assertThat(body.memberPermissions()) - .contains( - listOf( - RoleCreateParams.MemberPermission.builder() - .permission(Permission.CREATE) - .restrictObjectType(AclObjectType.ORGANIZATION) - .build() - ) + assertThat(body.memberPermissions().getOrNull()) + .containsExactly( + RoleCreateParams.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() ) - assertThat(body.memberRoles()).contains(listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) + assertThat(body.memberRoles().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.orgName()).contains("org_name") } @@ -64,7 +62,6 @@ internal class RoleCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleDeleteParamsTest.kt index 6552fe89..8a61140e 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleDeleteParamsTest.kt @@ -13,13 +13,12 @@ internal class RoleDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = RoleDeleteParams.builder().roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "roleId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleListPageResponseTest.kt new file mode 100644 index 00000000..0cdd38e4 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleListPageResponseTest.kt @@ -0,0 +1,91 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class RoleListPageResponseTest { + + @Test + fun create() { + val roleListPageResponse = + RoleListPageResponse.builder() + .addObject( + Role.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .addMemberPermission( + Role.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + assertThat(roleListPageResponse.objects()) + .containsExactly( + Role.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .addMemberPermission( + Role.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val roleListPageResponse = + RoleListPageResponse.builder() + .addObject( + Role.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .addMemberPermission( + Role.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + val roundtrippedRoleListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(roleListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedRoleListPageResponse).isEqualTo(roleListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleReplaceParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleReplaceParamsTest.kt index d278709c..5b3ce5ce 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleReplaceParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleReplaceParamsTest.kt @@ -2,7 +2,7 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -42,19 +42,17 @@ internal class RoleReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") assertThat(body.description()).contains("description") - assertThat(body.memberPermissions()) - .contains( - listOf( - RoleReplaceParams.MemberPermission.builder() - .permission(Permission.CREATE) - .restrictObjectType(AclObjectType.ORGANIZATION) - .build() - ) + assertThat(body.memberPermissions().getOrNull()) + .containsExactly( + RoleReplaceParams.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() ) - assertThat(body.memberRoles()).contains(listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) + assertThat(body.memberRoles().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.orgName()).contains("org_name") } @@ -64,7 +62,6 @@ internal class RoleReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("x") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleRetrieveParamsTest.kt index 72b41378..27d753fa 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleRetrieveParamsTest.kt @@ -13,13 +13,12 @@ internal class RoleRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = RoleRetrieveParams.builder().roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "roleId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleTest.kt index c3adf0e4..d057dcc7 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleTest.kt @@ -2,14 +2,17 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class RoleTest { @Test - fun createRole() { + fun create() { val role = Role.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -27,21 +30,49 @@ internal class RoleTest { .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(role).isNotNull + assertThat(role.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(role.name()).isEqualTo("name") assertThat(role.created()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) assertThat(role.deletedAt()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) assertThat(role.description()).contains("description") - assertThat(role.memberPermissions().get()) + assertThat(role.memberPermissions().getOrNull()) .containsExactly( Role.MemberPermission.builder() .permission(Permission.CREATE) .restrictObjectType(AclObjectType.ORGANIZATION) .build() ) - assertThat(role.memberRoles().get()).containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(role.memberRoles().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(role.orgId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(role.userId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val role = + Role.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .addMemberPermission( + Role.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val roundtrippedRole = + jsonMapper.readValue(jsonMapper.writeValueAsString(role), jacksonTypeRef()) + + assertThat(roundtrippedRole).isEqualTo(role) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleUpdateParamsTest.kt index 5108aba7..bfa8c9bf 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleUpdateParamsTest.kt @@ -2,7 +2,7 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -31,6 +31,16 @@ internal class RoleUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = + RoleUpdateParams.builder().roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -56,30 +66,26 @@ internal class RoleUpdateParamsTest { val body = params._body() - assertNotNull(body) - assertThat(body.addMemberPermissions()) - .contains( - listOf( - RoleUpdateParams.AddMemberPermission.builder() - .permission(Permission.CREATE) - .restrictObjectType(AclObjectType.ORGANIZATION) - .build() - ) + assertThat(body.addMemberPermissions().getOrNull()) + .containsExactly( + RoleUpdateParams.AddMemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() ) - assertThat(body.addMemberRoles()).contains(listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) + assertThat(body.addMemberRoles().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.description()).contains("description") assertThat(body.name()).contains("x") - assertThat(body.removeMemberPermissions()) - .contains( - listOf( - RoleUpdateParams.RemoveMemberPermission.builder() - .permission(Permission.CREATE) - .restrictObjectType(AclObjectType.ORGANIZATION) - .build() - ) + assertThat(body.removeMemberPermissions().getOrNull()) + .containsExactly( + RoleUpdateParams.RemoveMemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() ) - assertThat(body.removeMemberRoles()) - .contains(listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) + assertThat(body.removeMemberRoles().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } @Test @@ -88,18 +94,5 @@ internal class RoleUpdateParamsTest { RoleUpdateParams.builder().roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - RoleUpdateParams.builder().roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "roleId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ScoreSummaryTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ScoreSummaryTest.kt index e37b5561..163e2608 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ScoreSummaryTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ScoreSummaryTest.kt @@ -2,13 +2,15 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class ScoreSummaryTest { @Test - fun createScoreSummary() { + fun create() { val scoreSummary = ScoreSummary.builder() .improvements(0L) @@ -17,11 +19,32 @@ internal class ScoreSummaryTest { .score(0.0) .diff(-1.0) .build() - assertThat(scoreSummary).isNotNull + assertThat(scoreSummary.improvements()).isEqualTo(0L) assertThat(scoreSummary.name()).isEqualTo("name") assertThat(scoreSummary.regressions()).isEqualTo(0L) assertThat(scoreSummary.score()).isEqualTo(0.0) assertThat(scoreSummary.diff()).contains(-1.0) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val scoreSummary = + ScoreSummary.builder() + .improvements(0L) + .name("name") + .regressions(0L) + .score(0.0) + .diff(-1.0) + .build() + + val roundtrippedScoreSummary = + jsonMapper.readValue( + jsonMapper.writeValueAsString(scoreSummary), + jacksonTypeRef(), + ) + + assertThat(roundtrippedScoreSummary).isEqualTo(scoreSummary) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanAttributesTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanAttributesTest.kt index c8368446..30df044a 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanAttributesTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanAttributesTest.kt @@ -2,16 +2,32 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class SpanAttributesTest { @Test - fun createSpanAttributes() { + fun create() { val spanAttributes = SpanAttributes.builder().name("name").type(SpanType.LLM).build() - assertThat(spanAttributes).isNotNull + assertThat(spanAttributes.name()).contains("name") assertThat(spanAttributes.type()).contains(SpanType.LLM) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val spanAttributes = SpanAttributes.builder().name("name").type(SpanType.LLM).build() + + val roundtrippedSpanAttributes = + jsonMapper.readValue( + jsonMapper.writeValueAsString(spanAttributes), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSpanAttributes).isEqualTo(spanAttributes) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIFrameTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIFrameTest.kt index 13eb4eef..3c05ea3d 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIFrameTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIFrameTest.kt @@ -2,6 +2,8 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -9,7 +11,7 @@ import org.junit.jupiter.api.Test internal class SpanIFrameTest { @Test - fun createSpanIFrame() { + fun create() { val spanIFrame = SpanIFrame.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -22,7 +24,7 @@ internal class SpanIFrameTest { .postMessage(true) .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(spanIFrame).isNotNull + assertThat(spanIFrame.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(spanIFrame.name()).isEqualTo("name") assertThat(spanIFrame.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -34,4 +36,29 @@ internal class SpanIFrameTest { assertThat(spanIFrame.postMessage()).contains(true) assertThat(spanIFrame.userId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val spanIFrame = + SpanIFrame.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .url("url") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .postMessage(true) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val roundtrippedSpanIFrame = + jsonMapper.readValue( + jsonMapper.writeValueAsString(spanIFrame), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSpanIFrame).isEqualTo(spanIFrame) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeCreateParamsTest.kt index 16fcf240..b95ed798 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeCreateParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -32,7 +31,6 @@ internal class SpanIframeCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.url()).isEqualTo("url") @@ -51,7 +49,6 @@ internal class SpanIframeCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.url()).isEqualTo("url") diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeDeleteParamsTest.kt index a2f0c37f..09ce2983 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeDeleteParamsTest.kt @@ -15,15 +15,14 @@ internal class SpanIframeDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = SpanIframeDeleteParams.builder() .spanIframeId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "spanIframeId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeListPageResponseTest.kt new file mode 100644 index 00000000..86a3f694 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeListPageResponseTest.kt @@ -0,0 +1,76 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class SpanIframeListPageResponseTest { + + @Test + fun create() { + val spanIframeListPageResponse = + SpanIframeListPageResponse.builder() + .addObject( + SpanIFrame.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .url("url") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .postMessage(true) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + assertThat(spanIframeListPageResponse.objects()) + .containsExactly( + SpanIFrame.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .url("url") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .postMessage(true) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val spanIframeListPageResponse = + SpanIframeListPageResponse.builder() + .addObject( + SpanIFrame.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .url("url") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") + .postMessage(true) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + val roundtrippedSpanIframeListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(spanIframeListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSpanIframeListPageResponse).isEqualTo(spanIframeListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeReplaceParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeReplaceParamsTest.kt index f641330c..959f5fa4 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeReplaceParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeReplaceParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -32,7 +31,6 @@ internal class SpanIframeReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.url()).isEqualTo("url") @@ -51,7 +49,6 @@ internal class SpanIframeReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.url()).isEqualTo("url") diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeRetrieveParamsTest.kt index adab9365..885d2d46 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeRetrieveParamsTest.kt @@ -15,15 +15,14 @@ internal class SpanIframeRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = SpanIframeRetrieveParams.builder() .spanIframeId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(params).isNotNull - // path param "spanIframeId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeUpdateParamsTest.kt index fd52b975..4a255d60 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeUpdateParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -19,6 +18,18 @@ internal class SpanIframeUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = + SpanIframeUpdateParams.builder() + .spanIframeId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -32,7 +43,6 @@ internal class SpanIframeUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.description()).contains("description") assertThat(body.name()).contains("name") assertThat(body.postMessage()).contains(true) @@ -47,20 +57,5 @@ internal class SpanIframeUpdateParamsTest { .build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - SpanIframeUpdateParams.builder() - .spanIframeId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - assertThat(params).isNotNull - // path param "spanIframeId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SummarizeDatasetResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SummarizeDatasetResponseTest.kt index 78017764..58021961 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SummarizeDatasetResponseTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SummarizeDatasetResponseTest.kt @@ -2,13 +2,15 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class SummarizeDatasetResponseTest { @Test - fun createSummarizeDatasetResponse() { + fun create() { val summarizeDatasetResponse = SummarizeDatasetResponse.builder() .datasetName("dataset_name") @@ -17,7 +19,7 @@ internal class SummarizeDatasetResponseTest { .projectUrl("https://example.com") .dataSummary(DataSummary.builder().totalRecords(0L).build()) .build() - assertThat(summarizeDatasetResponse).isNotNull + assertThat(summarizeDatasetResponse.datasetName()).isEqualTo("dataset_name") assertThat(summarizeDatasetResponse.datasetUrl()).isEqualTo("https://example.com") assertThat(summarizeDatasetResponse.projectName()).isEqualTo("project_name") @@ -25,4 +27,25 @@ internal class SummarizeDatasetResponseTest { assertThat(summarizeDatasetResponse.dataSummary()) .contains(DataSummary.builder().totalRecords(0L).build()) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val summarizeDatasetResponse = + SummarizeDatasetResponse.builder() + .datasetName("dataset_name") + .datasetUrl("https://example.com") + .projectName("project_name") + .projectUrl("https://example.com") + .dataSummary(DataSummary.builder().totalRecords(0L).build()) + .build() + + val roundtrippedSummarizeDatasetResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(summarizeDatasetResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSummarizeDatasetResponse).isEqualTo(summarizeDatasetResponse) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SummarizeExperimentResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SummarizeExperimentResponseTest.kt index 2b332170..36badb29 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SummarizeExperimentResponseTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SummarizeExperimentResponseTest.kt @@ -3,13 +3,15 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class SummarizeExperimentResponseTest { @Test - fun createSummarizeExperimentResponse() { + fun create() { val summarizeExperimentResponse = SummarizeExperimentResponse.builder() .experimentName("experiment_name") @@ -51,7 +53,7 @@ internal class SummarizeExperimentResponseTest { .build() ) .build() - assertThat(summarizeExperimentResponse).isNotNull + assertThat(summarizeExperimentResponse.experimentName()).isEqualTo("experiment_name") assertThat(summarizeExperimentResponse.experimentUrl()).isEqualTo("https://example.com") assertThat(summarizeExperimentResponse.projectName()).isEqualTo("project_name") @@ -94,4 +96,58 @@ internal class SummarizeExperimentResponseTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val summarizeExperimentResponse = + SummarizeExperimentResponse.builder() + .experimentName("experiment_name") + .experimentUrl("https://example.com") + .projectName("project_name") + .projectUrl("https://example.com") + .comparisonExperimentName("comparison_experiment_name") + .metrics( + SummarizeExperimentResponse.Metrics.builder() + .putAdditionalProperty( + "foo", + JsonValue.from( + mapOf( + "improvements" to 0, + "metric" to 0, + "name" to "name", + "regressions" to 0, + "unit" to "unit", + "diff" to 0, + ) + ), + ) + .build() + ) + .scores( + SummarizeExperimentResponse.Scores.builder() + .putAdditionalProperty( + "foo", + JsonValue.from( + mapOf( + "improvements" to 0, + "name" to "name", + "regressions" to 0, + "score" to 0, + "diff" to -1, + ) + ), + ) + .build() + ) + .build() + + val roundtrippedSummarizeExperimentResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(summarizeExperimentResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSummarizeExperimentResponse).isEqualTo(summarizeExperimentResponse) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/UserListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/UserListPageResponseTest.kt new file mode 100644 index 00000000..58f9ef44 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/UserListPageResponseTest.kt @@ -0,0 +1,67 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UserListPageResponseTest { + + @Test + fun create() { + val userListPageResponse = + UserListPageResponse.builder() + .addObject( + User.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .avatarUrl("avatar_url") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .email("email") + .familyName("family_name") + .givenName("given_name") + .build() + ) + .build() + + assertThat(userListPageResponse.objects()) + .containsExactly( + User.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .avatarUrl("avatar_url") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .email("email") + .familyName("family_name") + .givenName("given_name") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val userListPageResponse = + UserListPageResponse.builder() + .addObject( + User.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .avatarUrl("avatar_url") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .email("email") + .familyName("family_name") + .givenName("given_name") + .build() + ) + .build() + + val roundtrippedUserListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(userListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUserListPageResponse).isEqualTo(userListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/UserRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/UserRetrieveParamsTest.kt index 6c4f828f..f684fdad 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/UserRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/UserRetrieveParamsTest.kt @@ -13,13 +13,12 @@ internal class UserRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = UserRetrieveParams.builder().userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - assertThat(params).isNotNull - // path param "userId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/UserTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/UserTest.kt index 56a1074a..49bab46a 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/UserTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/UserTest.kt @@ -2,6 +2,8 @@ package com.braintrustdata.api.models +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -9,7 +11,7 @@ import org.junit.jupiter.api.Test internal class UserTest { @Test - fun createUser() { + fun create() { val user = User.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -19,7 +21,7 @@ internal class UserTest { .familyName("family_name") .givenName("given_name") .build() - assertThat(user).isNotNull + assertThat(user.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(user.avatarUrl()).contains("avatar_url") assertThat(user.created()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) @@ -27,4 +29,23 @@ internal class UserTest { assertThat(user.familyName()).contains("family_name") assertThat(user.givenName()).contains("given_name") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val user = + User.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .avatarUrl("avatar_url") + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .email("email") + .familyName("family_name") + .givenName("given_name") + .build() + + val roundtrippedUser = + jsonMapper.readValue(jsonMapper.writeValueAsString(user), jacksonTypeRef()) + + assertThat(roundtrippedUser).isEqualTo(user) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewCreateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewCreateParamsTest.kt index c237c2ce..e86fd560 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewCreateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewCreateParamsTest.kt @@ -4,7 +4,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue import java.time.OffsetDateTime -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -96,7 +95,6 @@ internal class ViewCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) @@ -149,7 +147,6 @@ internal class ViewCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewDataSearchTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewDataSearchTest.kt index bd1ce88f..5a03bd80 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewDataSearchTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewDataSearchTest.kt @@ -3,13 +3,16 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class ViewDataSearchTest { @Test - fun createViewDataSearch() { + fun create() { val viewDataSearch = ViewDataSearch.builder() .addFilter(JsonValue.from(mapOf())) @@ -17,13 +20,34 @@ internal class ViewDataSearchTest { .addSort(JsonValue.from(mapOf())) .addTag(JsonValue.from(mapOf())) .build() - assertThat(viewDataSearch).isNotNull - assertThat(viewDataSearch.filter().get()) + + assertThat(viewDataSearch.filter().getOrNull()) + .containsExactly(JsonValue.from(mapOf())) + assertThat(viewDataSearch.match().getOrNull()) .containsExactly(JsonValue.from(mapOf())) - assertThat(viewDataSearch.match().get()) + assertThat(viewDataSearch.sort().getOrNull()) .containsExactly(JsonValue.from(mapOf())) - assertThat(viewDataSearch.sort().get()) + assertThat(viewDataSearch.tag().getOrNull()) .containsExactly(JsonValue.from(mapOf())) - assertThat(viewDataSearch.tag().get()).containsExactly(JsonValue.from(mapOf())) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val viewDataSearch = + ViewDataSearch.builder() + .addFilter(JsonValue.from(mapOf())) + .addMatch(JsonValue.from(mapOf())) + .addSort(JsonValue.from(mapOf())) + .addTag(JsonValue.from(mapOf())) + .build() + + val roundtrippedViewDataSearch = + jsonMapper.readValue( + jsonMapper.writeValueAsString(viewDataSearch), + jacksonTypeRef(), + ) + + assertThat(roundtrippedViewDataSearch).isEqualTo(viewDataSearch) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewDataTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewDataTest.kt index b1dabd9e..28b304e1 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewDataTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewDataTest.kt @@ -3,13 +3,15 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class ViewDataTest { @Test - fun createViewData() { + fun create() { val viewData = ViewData.builder() .search( @@ -21,7 +23,7 @@ internal class ViewDataTest { .build() ) .build() - assertThat(viewData).isNotNull + assertThat(viewData.search()) .contains( ViewDataSearch.builder() @@ -32,4 +34,28 @@ internal class ViewDataTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val viewData = + ViewData.builder() + .search( + ViewDataSearch.builder() + .addFilter(JsonValue.from(mapOf())) + .addMatch(JsonValue.from(mapOf())) + .addSort(JsonValue.from(mapOf())) + .addTag(JsonValue.from(mapOf())) + .build() + ) + .build() + + val roundtrippedViewData = + jsonMapper.readValue( + jsonMapper.writeValueAsString(viewData), + jacksonTypeRef(), + ) + + assertThat(roundtrippedViewData).isEqualTo(viewData) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewDeleteParamsTest.kt index 6d6c784c..e6224941 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewDeleteParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewDeleteParamsTest.kt @@ -2,7 +2,6 @@ package com.braintrustdata.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -18,7 +17,7 @@ internal class ViewDeleteParamsTest { } @Test - fun body() { + fun pathParams() { val params = ViewDeleteParams.builder() .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -26,15 +25,13 @@ internal class ViewDeleteParamsTest { .objectType(AclObjectType.ORGANIZATION) .build() - val body = params._body() - - assertNotNull(body) - assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") } @Test - fun bodyWithoutOptionalFields() { + fun body() { val params = ViewDeleteParams.builder() .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -44,23 +41,7 @@ internal class ViewDeleteParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) } - - @Test - fun getPathParam() { - val params = - ViewDeleteParams.builder() - .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .objectType(AclObjectType.ORGANIZATION) - .build() - assertThat(params).isNotNull - // path param "viewId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewListPageResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewListPageResponseTest.kt new file mode 100644 index 00000000..9f6575f0 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewListPageResponseTest.kt @@ -0,0 +1,164 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ViewListPageResponseTest { + + @Test + fun create() { + val viewListPageResponse = + ViewListPageResponse.builder() + .addObject( + View.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .viewType(View.ViewType.PROJECTS) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .options( + ViewOptions.builder() + .addColumnOrder("string") + .columnSizing( + ViewOptions.ColumnSizing.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .columnVisibility( + ViewOptions.ColumnVisibility.builder() + .putAdditionalProperty("foo", JsonValue.from(true)) + .build() + ) + .grouping("grouping") + .layout("layout") + .rowHeight("rowHeight") + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .viewData( + ViewData.builder() + .search( + ViewDataSearch.builder() + .addFilter(JsonValue.from(mapOf())) + .addMatch(JsonValue.from(mapOf())) + .addSort(JsonValue.from(mapOf())) + .addTag(JsonValue.from(mapOf())) + .build() + ) + .build() + ) + .build() + ) + .build() + + assertThat(viewListPageResponse.objects()) + .containsExactly( + View.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .viewType(View.ViewType.PROJECTS) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .options( + ViewOptions.builder() + .addColumnOrder("string") + .columnSizing( + ViewOptions.ColumnSizing.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .columnVisibility( + ViewOptions.ColumnVisibility.builder() + .putAdditionalProperty("foo", JsonValue.from(true)) + .build() + ) + .grouping("grouping") + .layout("layout") + .rowHeight("rowHeight") + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .viewData( + ViewData.builder() + .search( + ViewDataSearch.builder() + .addFilter(JsonValue.from(mapOf())) + .addMatch(JsonValue.from(mapOf())) + .addSort(JsonValue.from(mapOf())) + .addTag(JsonValue.from(mapOf())) + .build() + ) + .build() + ) + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val viewListPageResponse = + ViewListPageResponse.builder() + .addObject( + View.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .viewType(View.ViewType.PROJECTS) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .options( + ViewOptions.builder() + .addColumnOrder("string") + .columnSizing( + ViewOptions.ColumnSizing.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .columnVisibility( + ViewOptions.ColumnVisibility.builder() + .putAdditionalProperty("foo", JsonValue.from(true)) + .build() + ) + .grouping("grouping") + .layout("layout") + .rowHeight("rowHeight") + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .viewData( + ViewData.builder() + .search( + ViewDataSearch.builder() + .addFilter(JsonValue.from(mapOf())) + .addMatch(JsonValue.from(mapOf())) + .addSort(JsonValue.from(mapOf())) + .addTag(JsonValue.from(mapOf())) + .build() + ) + .build() + ) + .build() + ) + .build() + + val roundtrippedViewListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(viewListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedViewListPageResponse).isEqualTo(viewListPageResponse) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewOptionsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewOptionsTest.kt index 1c0aceec..3407df7f 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewOptionsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewOptionsTest.kt @@ -3,13 +3,16 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class ViewOptionsTest { @Test - fun createViewOptions() { + fun create() { val viewOptions = ViewOptions.builder() .addColumnOrder("string") @@ -27,8 +30,8 @@ internal class ViewOptionsTest { .layout("layout") .rowHeight("rowHeight") .build() - assertThat(viewOptions).isNotNull - assertThat(viewOptions.columnOrder().get()).containsExactly("string") + + assertThat(viewOptions.columnOrder().getOrNull()).containsExactly("string") assertThat(viewOptions.columnSizing()) .contains( ViewOptions.ColumnSizing.builder() @@ -45,4 +48,34 @@ internal class ViewOptionsTest { assertThat(viewOptions.layout()).contains("layout") assertThat(viewOptions.rowHeight()).contains("rowHeight") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val viewOptions = + ViewOptions.builder() + .addColumnOrder("string") + .columnSizing( + ViewOptions.ColumnSizing.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .columnVisibility( + ViewOptions.ColumnVisibility.builder() + .putAdditionalProperty("foo", JsonValue.from(true)) + .build() + ) + .grouping("grouping") + .layout("layout") + .rowHeight("rowHeight") + .build() + + val roundtrippedViewOptions = + jsonMapper.readValue( + jsonMapper.writeValueAsString(viewOptions), + jacksonTypeRef(), + ) + + assertThat(roundtrippedViewOptions).isEqualTo(viewOptions) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewReplaceParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewReplaceParamsTest.kt index 6dd1cd82..7b715533 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewReplaceParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewReplaceParamsTest.kt @@ -4,7 +4,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue import java.time.OffsetDateTime -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -96,7 +95,6 @@ internal class ViewReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) @@ -149,7 +147,6 @@ internal class ViewReplaceParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.name()).isEqualTo("name") assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewRetrieveParamsTest.kt index d73a583b..84cc78de 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewRetrieveParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewRetrieveParamsTest.kt @@ -18,7 +18,7 @@ internal class ViewRetrieveParamsTest { } @Test - fun queryParams() { + fun pathParams() { val params = ViewRetrieveParams.builder() .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -26,19 +26,13 @@ internal class ViewRetrieveParamsTest { .objectType(AclObjectType.ORGANIZATION) .build() - val queryParams = params._queryParams() - - assertThat(queryParams) - .isEqualTo( - QueryParams.builder() - .put("object_id", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .put("object_type", "organization") - .build() - ) + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") } @Test - fun queryParamsWithoutOptionalFields() { + fun queryParams() { val params = ViewRetrieveParams.builder() .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -56,19 +50,4 @@ internal class ViewRetrieveParamsTest { .build() ) } - - @Test - fun getPathParam() { - val params = - ViewRetrieveParams.builder() - .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .objectType(AclObjectType.ORGANIZATION) - .build() - assertThat(params).isNotNull - // path param "viewId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewTest.kt index e8ba2a61..7dca73f4 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewTest.kt @@ -3,6 +3,8 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.jsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -10,7 +12,7 @@ import org.junit.jupiter.api.Test internal class ViewTest { @Test - fun createView() { + fun create() { val view = View.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -52,7 +54,7 @@ internal class ViewTest { .build() ) .build() - assertThat(view).isNotNull + assertThat(view.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(view.name()).isEqualTo("name") assertThat(view.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -94,4 +96,55 @@ internal class ViewTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val view = + View.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .viewType(View.ViewType.PROJECTS) + .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .options( + ViewOptions.builder() + .addColumnOrder("string") + .columnSizing( + ViewOptions.ColumnSizing.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .columnVisibility( + ViewOptions.ColumnVisibility.builder() + .putAdditionalProperty("foo", JsonValue.from(true)) + .build() + ) + .grouping("grouping") + .layout("layout") + .rowHeight("rowHeight") + .build() + ) + .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .viewData( + ViewData.builder() + .search( + ViewDataSearch.builder() + .addFilter(JsonValue.from(mapOf())) + .addMatch(JsonValue.from(mapOf())) + .addSort(JsonValue.from(mapOf())) + .addTag(JsonValue.from(mapOf())) + .build() + ) + .build() + ) + .build() + + val roundtrippedView = + jsonMapper.readValue(jsonMapper.writeValueAsString(view), jacksonTypeRef()) + + assertThat(roundtrippedView).isEqualTo(view) + } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewUpdateParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewUpdateParamsTest.kt index 36044079..f2e0332c 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewUpdateParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewUpdateParamsTest.kt @@ -3,7 +3,6 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -51,6 +50,20 @@ internal class ViewUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = + ViewUpdateParams.builder() + .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -95,7 +108,6 @@ internal class ViewUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) assertThat(body.name()).contains("name") @@ -146,23 +158,7 @@ internal class ViewUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) } - - @Test - fun getPathParam() { - val params = - ViewUpdateParams.builder() - .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .objectType(AclObjectType.ORGANIZATION) - .build() - assertThat(params).isNotNull - // path param "viewId" - assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/ErrorHandlingTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/ErrorHandlingTest.kt index 2716a7ab..d1b745a7 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/ErrorHandlingTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/ErrorHandlingTest.kt @@ -8,7 +8,6 @@ import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.jsonMapper import com.braintrustdata.api.errors.BadRequestException -import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.errors.BraintrustException import com.braintrustdata.api.errors.InternalServerException import com.braintrustdata.api.errors.NotFoundException @@ -29,18 +28,17 @@ import org.assertj.core.api.Assertions.entry import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.api.parallel.ResourceLock @WireMockTest +@ResourceLock("https://github.com/wiremock/wiremock/issues/169") internal class ErrorHandlingTest { companion object { - private val ERROR: BraintrustError = - BraintrustError.builder() - .putAdditionalProperty("errorProperty", JsonValue.from("42")) - .build() + private val ERROR_JSON: JsonValue = JsonValue.from(mapOf("errorProperty" to "42")) - private val ERROR_JSON: ByteArray = jsonMapper().writeValueAsBytes(ERROR) + private val ERROR_JSON_BYTES: ByteArray = jsonMapper().writeValueAsBytes(ERROR_JSON) private const val HEADER_NAME: String = "Error-Header" @@ -65,7 +63,9 @@ internal class ErrorHandlingTest { val projectService = client.projects() stubFor( post(anyUrl()) - .willReturn(status(400).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON)) + .willReturn( + status(400).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) val e = @@ -76,8 +76,8 @@ internal class ErrorHandlingTest { } assertThat(e.statusCode()).isEqualTo(400) - assertThat(e.error()).isEqualTo(ERROR) assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test @@ -85,7 +85,9 @@ internal class ErrorHandlingTest { val projectService = client.projects() stubFor( post(anyUrl()) - .willReturn(status(401).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON)) + .willReturn( + status(401).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) val e = @@ -96,8 +98,8 @@ internal class ErrorHandlingTest { } assertThat(e.statusCode()).isEqualTo(401) - assertThat(e.error()).isEqualTo(ERROR) assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test @@ -105,7 +107,9 @@ internal class ErrorHandlingTest { val projectService = client.projects() stubFor( post(anyUrl()) - .willReturn(status(403).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON)) + .willReturn( + status(403).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) val e = @@ -116,8 +120,8 @@ internal class ErrorHandlingTest { } assertThat(e.statusCode()).isEqualTo(403) - assertThat(e.error()).isEqualTo(ERROR) assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test @@ -125,7 +129,9 @@ internal class ErrorHandlingTest { val projectService = client.projects() stubFor( post(anyUrl()) - .willReturn(status(404).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON)) + .willReturn( + status(404).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) val e = @@ -136,8 +142,8 @@ internal class ErrorHandlingTest { } assertThat(e.statusCode()).isEqualTo(404) - assertThat(e.error()).isEqualTo(ERROR) assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test @@ -145,7 +151,9 @@ internal class ErrorHandlingTest { val projectService = client.projects() stubFor( post(anyUrl()) - .willReturn(status(422).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON)) + .willReturn( + status(422).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) val e = @@ -156,8 +164,8 @@ internal class ErrorHandlingTest { } assertThat(e.statusCode()).isEqualTo(422) - assertThat(e.error()).isEqualTo(ERROR) assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test @@ -165,7 +173,9 @@ internal class ErrorHandlingTest { val projectService = client.projects() stubFor( post(anyUrl()) - .willReturn(status(429).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON)) + .willReturn( + status(429).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) val e = @@ -176,8 +186,8 @@ internal class ErrorHandlingTest { } assertThat(e.statusCode()).isEqualTo(429) - assertThat(e.error()).isEqualTo(ERROR) assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test @@ -185,7 +195,9 @@ internal class ErrorHandlingTest { val projectService = client.projects() stubFor( post(anyUrl()) - .willReturn(status(500).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON)) + .willReturn( + status(500).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) val e = @@ -196,8 +208,8 @@ internal class ErrorHandlingTest { } assertThat(e.statusCode()).isEqualTo(500) - assertThat(e.error()).isEqualTo(ERROR) assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test @@ -205,7 +217,9 @@ internal class ErrorHandlingTest { val projectService = client.projects() stubFor( post(anyUrl()) - .willReturn(status(999).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON)) + .willReturn( + status(999).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) val e = @@ -216,8 +230,8 @@ internal class ErrorHandlingTest { } assertThat(e.statusCode()).isEqualTo(999) - assertThat(e.error()).isEqualTo(ERROR) assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/ServiceParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/ServiceParamsTest.kt index 9e25370e..436926c8 100755 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/ServiceParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/ServiceParamsTest.kt @@ -18,8 +18,10 @@ import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo import com.github.tomakehurst.wiremock.junit5.WireMockTest 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 ServiceParamsTest { private lateinit var client: BraintrustClient diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/EnvVarServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/EnvVarServiceAsyncTest.kt index 9d95d5e8..f17f8a4e 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/EnvVarServiceAsyncTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/EnvVarServiceAsyncTest.kt @@ -91,7 +91,7 @@ internal class EnvVarServiceAsyncTest { .build() val envVarServiceAsync = client.envVars() - val envVarFuture = + val envVarsFuture = envVarServiceAsync.list( EnvVarListParams.builder() .envVarName("env_var_name") @@ -102,8 +102,8 @@ internal class EnvVarServiceAsyncTest { .build() ) - val envVar = envVarFuture.get() - envVar.validate() + val envVars = envVarsFuture.get() + envVars.validate() } @Test diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/EnvVarServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/EnvVarServiceTest.kt index 77382bfc..d57db964 100644 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/EnvVarServiceTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/EnvVarServiceTest.kt @@ -88,7 +88,7 @@ internal class EnvVarServiceTest { .build() val envVarService = client.envVars() - val envVar = + val envVars = envVarService.list( EnvVarListParams.builder() .envVarName("env_var_name") @@ -99,7 +99,7 @@ internal class EnvVarServiceTest { .build() ) - envVar.validate() + envVars.validate() } @Test diff --git a/braintrust-java-example/build.gradle.kts b/braintrust-java-example/build.gradle.kts index c64a1556..298fe690 100644 --- a/braintrust-java-example/build.gradle.kts +++ b/braintrust-java-example/build.gradle.kts @@ -1,9 +1,12 @@ plugins { - id("braintrust.kotlin") - id("java") + id("braintrust.java") application } +repositories { + mavenCentral() +} + dependencies { implementation(project(":braintrust-java")) } diff --git a/build.gradle.kts b/build.gradle.kts index 3a613beb..d8afa3b2 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -8,7 +8,7 @@ repositories { allprojects { group = "com.braintrustdata.api" - version = "0.8.0" // x-release-please-version + version = "0.9.0" // x-release-please-version } subprojects { diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index d1ed374d..778c89de 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -1,6 +1,6 @@ plugins { `kotlin-dsl` - kotlin("jvm") version "2.1.10" + kotlin("jvm") version "1.9.20" id("com.vanniktech.maven.publish") version "0.28.0" } @@ -11,6 +11,6 @@ repositories { dependencies { implementation("com.diffplug.spotless:spotless-plugin-gradle:7.0.2") - implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:2.1.10") + 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/braintrust.java.gradle.kts b/buildSrc/src/main/kotlin/braintrust.java.gradle.kts index 597b6e80..e39d9ac6 100755 --- a/buildSrc/src/main/kotlin/braintrust.java.gradle.kts +++ b/buildSrc/src/main/kotlin/braintrust.java.gradle.kts @@ -23,6 +23,9 @@ java { toolchain { languageVersion.set(JavaLanguageVersion.of(17)) } + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 } tasks.withType().configureEach { diff --git a/buildSrc/src/main/kotlin/braintrust.kotlin.gradle.kts b/buildSrc/src/main/kotlin/braintrust.kotlin.gradle.kts index ff8a82d8..14b60c20 100755 --- a/buildSrc/src/main/kotlin/braintrust.kotlin.gradle.kts +++ b/buildSrc/src/main/kotlin/braintrust.kotlin.gradle.kts @@ -1,6 +1,6 @@ import com.diffplug.gradle.spotless.SpotlessExtension import org.jetbrains.kotlin.gradle.dsl.JvmTarget -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import org.jetbrains.kotlin.gradle.dsl.KotlinVersion plugins { id("braintrust.java") @@ -9,32 +9,34 @@ plugins { kotlin { jvmToolchain { - languageVersion.set(JavaLanguageVersion.of(17)) + languageVersion.set(JavaLanguageVersion.of(21)) } -} - -configure { - kotlin { - ktfmt().kotlinlangStyle() - toggleOffOn() - } -} -tasks.withType().configureEach { compilerOptions { - allWarningsAsErrors = true freeCompilerArgs = listOf( "-Xjvm-default=all", "-Xjdk-release=1.8", // Suppress deprecation warnings because we may still reference and test deprecated members. - "-Xsuppress-warning=DEPRECATION" + // TODO: Replace with `-Xsuppress-warning=DEPRECATION` once we use Kotlin compiler 2.1.0+. + "-nowarn", + // Use as many threads as there are CPU cores on the machine for compilation. + "-Xbackend-threads=0", ) jvmTarget.set(JvmTarget.JVM_1_8) + languageVersion.set(KotlinVersion.KOTLIN_1_8) + apiVersion.set(KotlinVersion.KOTLIN_1_8) + coreLibrariesVersion = "1.8.0" + } +} + +configure { + kotlin { + ktfmt().kotlinlangStyle() + toggleOffOn() } } -// Run tests in parallel to some degree. tasks.withType().configureEach { - maxParallelForks = (Runtime.getRuntime().availableProcessors() / 2).coerceAtLeast(1) - forkEvery = 100 + systemProperty("junit.jupiter.execution.parallel.enabled", true) + systemProperty("junit.jupiter.execution.parallel.mode.default", "concurrent") } diff --git a/gradle.properties b/gradle.properties index 0c8d4ded..ff76593f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,17 @@ 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=\ + -Xms1g \ + -Xmx4g \ + -XX:+UseParallelGC \ + -XX:InitialCodeCacheSize=256m \ + -XX:ReservedCodeCacheSize=1G \ + -XX:MetaspaceSize=256m \ + -XX:TieredStopAtLevel=1 \ + -XX:GCTimeRatio=4 \ + -XX:CICompilerCount=4 \ + -XX:+OptimizeStringConcat \ + -XX:+UseStringDeduplication